conversations
listlengths
2
3
source
stringclasses
1 value
stack
stringclasses
1 value
[ { "from": "human", "value": "Add test for async/await combined with const-generics.\n" }, { "from": "gpt", "value": "// edition:2018\n// check-pass\n// revisions: full min\n#![cfg_attr(full, feature(const_generics))]\n#![cfg_attr(full, allow(incomplete_features))]\n#![cfg_attr(min, feature(min_const_generics))]\n\nconst SIZE: usize = 16;\n\nstruct Bar<const H: usize> {}\n\nstruct Foo<const H: usize> {}\n\nimpl<const H: usize> Foo<H> {\n async fn biz(_: &[[u8; SIZE]]) -> Vec<()> {\n vec![]\n }\n\n pub async fn baz(&self) -> Bar<H> {\n Self::biz(&vec![]).await;\n Bar {}\n }\n}\n\nfn main() { }\n" } ]
rust
chosen
[ { "from": "human", "value": "test(vm): Add a test to check that marshalled references cannot escape\n" }, { "from": "gpt", "value": "extern crate embed_lang;\nuse embed_lang::new_vm;\nuse embed_lang::vm::vm::Value;\nuse embed_lang::vm::api::{VMType, Getable};\nuse embed_lang::vm::gc::Traverseable;\n\nuse std::cell::Cell;\n\nstruct Test<'vm>(Cell<&'vm str>);\n\nimpl<'vm> Traverseable for Test<'vm> { }\nimpl<'vm> VMType for Test<'vm> {\n type Type = Test<'static>;\n}\n\nfn f<'vm>(test: &'vm Test<'vm>, s: &'vm str) {\n test.0.set(s);\n}\n\nfn main() {\n let vm = new_vm();\n vm.define_global(\"f\", f as fn (_, _));\n //~^ Error `vm` does not live long enough\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Create a example PPM program\n\nThe program outputs a checkerboard\n" }, { "from": "gpt", "value": "extern crate scratchapixel;\n\nuse std::fs::File;\n\nuse scratchapixel::ppm::rgb::RGB;\nuse scratchapixel::ppm::format::PPM;\n\n\nfn main() {\n let white = RGB { r: 255, g: 255, b: 255 };\n let black = RGB { r: 0, g: 0, b: 0 };\n let red = RGB { r: 255, g: 0, b: 0 };\n let mut image: PPM = PPM::new(64, 64);\n for y in 0..64 {\n let parity_y = (y / 8) % 2;\n for x in 0..64 {\n let parity_x = (x / 8) % 2;\n let color = match (parity_y + parity_x) % 2 {\n 0 => black,\n 1 => white,\n _ => red\n };\n image.set_pixel(x, y, color);\n }\n }\n\n match File::create(\"resources/example.use_ppm.ppm\") {\n Ok(file) => {\n match image.write_file(file) {\n Ok(_) => println!(\"wrote file\"),\n Err(_) => println!(\"could not write file\")\n }\n }\n Err(_) => println!(\"could not create file\")\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add GitError algebraic data type\n" }, { "from": "gpt", "value": "use std::fmt;\n\npub enum GitError {\n CorruptedRepository(&'static str),\n CorruptedCommit(&'static str)\n}\n\nimpl fmt::Show for GitError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match *self {\n CorruptedCommit(s) => write!(f, \"CorruptedCommit: {}\", s),\n CorruptedRepository(s) => write!(f, \"CorruptedRepository: {}\", s),\n }\n }\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add redirector to simplify imports.\n" }, { "from": "gpt", "value": "/* This file exists just to make it easier to import things inside of\n ./geom/ without specifying the file they came out of imports.\n \nNote that you still must define each of the files as a module in\ngeom.rc. This is not ideal and may be changed in the future. */\n\npub use matrix::Matrix4;\npub use matrix2d::Matrix2D;\npub use point::Point2D;\npub use rect::Rect;\npub use size::Size2D;\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test to check that we do not get a cycle due to resolving `Self::Bar` in the where clauses\n" }, { "from": "gpt", "value": "// check-pass\n\n// Test that we do not get a cycle due to\n// resolving `Self::Bar` in the where clauses\n// on a trait definition (in particular, in\n// a where clause that is defining a superpredicate).\n\ntrait Foo {\n type Bar;\n}\ntrait Qux\nwhere\n Self: Foo,\n Self: AsRef<Self::Bar>,\n{\n}\ntrait Foo2 {}\n\ntrait Qux2\nwhere\n Self: Foo2,\n Self: AsRef<Self::Bar>,\n{\n type Bar;\n}\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update for changes in rustc.\n" }, { "from": "human", "value": "#![feature(\n btree_range,\n collections,\n collections_bound,\n question_mark,\n rustc_private,\n pub_restricted,\n)]\n\n// From rustc.\n#[macro_use] extern crate rustc;\nextern crate rustc_borrowck;\nextern crate rustc_data_structures;\nextern crate rustc_mir;\nextern crate rustc_const_math;\nextern crate syntax;\n#[macro_use] extern crate log;\nextern crate log_settings;\n\n// From crates.io.\nextern crate byteorder;\n\nmod error;\nmod interpreter;\nmod memory;\nmod primval;\n\npub use error::{\n EvalError,\n EvalResult,\n};\n\npub use interpreter::{\n CachedMir,\n EvalContext,\n Frame,\n eval_main,\n run_mir_passes,\n StackPopCleanup,\n};\n\npub use memory::{\n Memory,\n Pointer,\n AllocId,\n};\n" }, { "from": "gpt", "value": "#![feature(\n btree_range,\n collections,\n collections_bound,\n rustc_private,\n pub_restricted,\n)]\n\n// From rustc.\n#[macro_use] extern crate rustc;\nextern crate rustc_borrowck;\nextern crate rustc_data_structures;\nextern crate rustc_mir;\nextern crate rustc_const_math;\nextern crate syntax;\n#[macro_use] extern crate log;\nextern crate log_settings;\n\n// From crates.io.\nextern crate byteorder;\n\nmod error;\nmod interpreter;\nmod memory;\nmod primval;\n\npub use error::{\n EvalError,\n EvalResult,\n};\n\npub use interpreter::{\n CachedMir,\n EvalContext,\n Frame,\n eval_main,\n run_mir_passes,\n StackPopCleanup,\n};\n\npub use memory::{\n Memory,\n Pointer,\n AllocId,\n};\n" } ]
rust
chosen
[ { "from": "human", "value": "Check in a forgotten new file\n" }, { "from": "gpt", "value": "import syntax::ast::*;\nimport syntax::visit;\nimport driver::session::session;\n\ntype ctx = {in_loop: bool, can_ret: bool};\n\nfn check_crate(sess: session, crate: @crate) {\n visit::visit_crate(*crate, {in_loop: false,can_ret: true}, visit::mk_vt(@{\n visit_item: {|i, _cx, v|\n visit::visit_item(i, {in_loop: false, can_ret: true}, v);\n },\n visit_expr: {|e: @expr, cx: ctx, v: visit::vt<ctx>|\n alt e.node {\n expr_for(_, e, b) | expr_while(e, b) | expr_do_while(b, e) {\n v.visit_expr(e, cx, v);\n v.visit_block(b, {in_loop: true with cx}, v);\n }\n expr_loop(b) {\n v.visit_block(b, {in_loop: true with cx}, v);\n }\n expr_fn(_, _, _, _) {\n visit::visit_expr(e, {in_loop: false, can_ret: true}, v);\n }\n expr_fn_block(fn_decl, blk) {\n visit::visit_expr(e, {in_loop: false, can_ret: false}, v);\n }\n expr_break {\n if !cx.in_loop {\n sess.span_err(e.span, \"`break` outside of loop\");\n }\n }\n expr_cont {\n if !cx.in_loop {\n sess.span_err(e.span, \"`cont` outside of loop\");\n }\n }\n expr_ret(oe) {\n if !cx.can_ret {\n sess.span_err(e.span, \"`ret` in block function\");\n }\n visit::visit_expr_opt(oe, cx, v);\n }\n expr_be(re) {\n if !cx.can_ret {\n sess.span_err(e.span, \"`be` in block function\");\n }\n v.visit_expr(re, cx, v);\n }\n _ { visit::visit_expr(e, cx, v); }\n }\n }\n with *visit::default_visitor()\n }));\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add test for none-delimited attribute on an item\n" }, { "from": "gpt", "value": "#[macro_use]\nmod macros;\n\nuse proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};\nuse quote::quote;\nuse std::iter::FromIterator;\nuse syn::Item;\n\n#[test]\nfn test_macro_variable_attr() {\n // mimics the token stream corresponding to `$attr fn f() {}`\n let tokens = TokenStream::from_iter(vec![\n TokenTree::Group(Group::new(Delimiter::None, quote! { #[test] })),\n TokenTree::Ident(Ident::new(\"fn\", Span::call_site())),\n TokenTree::Ident(Ident::new(\"f\", Span::call_site())),\n TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())),\n TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())),\n ]);\n\n snapshot!(tokens as Item, @r###\"\n Item::Fn {\n attrs: [\n Attribute {\n style: Outer,\n path: Path {\n segments: [\n PathSegment {\n ident: \"test\",\n arguments: None,\n },\n ],\n },\n tokens: TokenStream(``),\n },\n ],\n vis: Inherited,\n sig: Signature {\n ident: \"f\",\n generics: Generics,\n output: Default,\n },\n block: Block,\n }\n \"###);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a testkit for HTTP cache integration tests.\n\nDerived from cargo's.\n" }, { "from": "gpt", "value": "use std::cell::Cell;\nuse std::env;\nuse std::fs;\nuse std::path::PathBuf;\nuse std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};\n\nfn global_test_root() -> PathBuf {\n let mut path = env::current_exe().unwrap();\n path.pop(); // chop off exe name\n path.pop(); // chop off 'debug'\n\n // If `cargo test` is run manually then our path looks like\n // `target/debug/foo`, in which case our `path` is already pointing at\n // `target`. If, however, `cargo test --target $target` is used then the\n // output is `target/$target/debug/foo`, so our path is pointing at\n // `target/$target`. Here we conditionally pop the `$target` name.\n if path.file_name().and_then(|s| s.to_str()) != Some(\"target\") {\n path.pop();\n }\n\n path.join(\"int-test\")\n}\n\nfn test_root() -> PathBuf {\n let root = global_test_root();\n\n static NEXT_TEST_NUM: AtomicUsize = ATOMIC_USIZE_INIT;\n thread_local!(static TEST_NUM: usize = NEXT_TEST_NUM.fetch_add(1, Ordering::SeqCst));\n let root = root.join(&TEST_NUM.with(|my_id| format!(\"t{}\", my_id)));\n\n thread_local!(static TEST_ROOT_INIT: Cell<bool> = Cell::new(false));\n TEST_ROOT_INIT.with(|i| {\n if i.get() {\n return;\n }\n i.set(true);\n fs::remove_dir_all(&root).expect(\"removing root\");\n debug!(\"deleted root {}\", root.display());\n });\n\n root\n}\n\npub fn test_home() -> PathBuf {\n test_root().join(\"home\")\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Test that fn preconditions get typechecked\n" }, { "from": "gpt", "value": "// Tests that the typechecker checks constraints\n// error-pattern:mismatched types: expected uint but found u8\nuse std;\nimport std::uint;\n\nfn enum_chars(start:u8, end:u8) : uint::le(start, end) -> [char] {\n let i = start;\n let r = [];\n while (i <= end) {\n r += [i as char];\n i += (1u as u8);\n }\n ret r;\n}\n\nfn main() {\n log (enum_chars('a' as u8, 'z' as u8));\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add another test for !\n" }, { "from": "gpt", "value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(never_type)]\n\ntrait StringifyType {\n fn stringify_type() -> &'static str;\n}\n\nimpl StringifyType for ! {\n fn stringify_type() -> &'static str {\n \"!\"\n }\n}\n\nfn maybe_stringify<T: StringifyType>(opt: Option<T>) -> &'static str {\n match opt {\n Some(_) => T::stringify_type(),\n None => \"none\",\n } \n}\n\nfn main() {\n println!(\"! is {}\", <!>::stringify_type());\n println!(\"None is {}\", maybe_stringify(None::<!>));\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test case for previous commit\n" }, { "from": "gpt", "value": "// -*- rust -*-\n// xfail-pretty\n\nenum color {\n red,\n green,\n blue\n}\n\nfn main() {\n log(error, alt red {\n red => { 1 }\n green => { 2 }\n blue => { 3 }\n });\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test for unique boxes as fn args\n\nIssue #409\n" }, { "from": "gpt", "value": "fn f(i: ~int) {\n assert *i == 100;\n}\n\nfn main() {\n f(~100);\n let i = ~100;\n f(i);\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add test for assoc consts.\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(associated_consts)]\n\ntrait Foo {\n const ID: i32;\n}\n\nimpl Foo for i32 {\n const ID: i32 = 1;\n}\n\nfn main() {\n assert_eq!(1, <i32 as Foo>::ID);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a regression test for FromIterator of OscArray\n" }, { "from": "gpt", "value": "extern crate rosc;\n\nuse rosc::{OscArray, OscType};\n\n#[test]\nfn test_osc_array_from_iter() {\n use std::iter::FromIterator;\n let iter = (0..3).map(|i| OscType::Int(i));\n let osc_arr = OscArray::from_iter(iter);\n assert_eq!(\n osc_arr,\n OscArray {\n content: vec![OscType::Int(0), OscType::Int(1), OscType::Int(2)]\n }\n );\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add rust code for perfect-numbers\n\nIt passed all test cases\n" }, { "from": "gpt", "value": "#[derive(Debug, PartialEq)]\npub enum Classification {\n Perfect,\n Abundant,\n Deficient,\n}\n\npub fn classify(number: u64) -> Result<Classification, &'static str> {\n if number < 1 {\n return Err(\"Number must be positive\");\n }\n\n let sum: u64 = (1..number / 2 + 1).filter(|x| number % x == 0).sum();\n\n if sum == number {\n Ok(Classification::Perfect)\n } else if sum > number {\n Ok(Classification::Abundant)\n } else {\n Ok(Classification::Deficient)\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for fix duplicate display of E0502\n" }, { "from": "gpt", "value": "// Copyright 2017 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nfn do_something<T>(collection: &mut Vec<T>) {\n let _a = &collection;\n collection.swap(1, 2); //~ ERROR E0502\n}\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for uint and negative literals as discriminants\n" }, { "from": "gpt", "value": "enum Animal {\n Cat = 0u,\n Dog = 1u,\n Horse = 2u,\n Snake = 3u\n}\n\nenum Hero {\n Batman = -1,\n Superman = -2,\n Ironman = -3,\n Spiderman = -4\n}\n\nfn main() {\n let pet: Animal = Snake;\n let hero: Hero = Superman;\n assert!(pet as uint == 3);\n assert!(hero as int == -2);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use NOTE instead of error-pattern directive\n" }, { "from": "human", "value": "// Copyright 2017 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// error-pattern:`main` can only return types like `()` that implement std::process::Termination, no\nfn main() -> i32 {\n 0\n}\n" }, { "from": "gpt", "value": "// Copyright 2017 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nfn main() -> i32 {\n//~^ ERROR `i32: std::process::Termination` is not satisfied\n//~| NOTE `main` can only return types like `()` that implement std::process::Termination, not `i32`\n 0\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add 7 segment display example\n" }, { "from": "gpt", "value": "#![no_std]\n\nextern crate tock;\n\nconst DATA_PIN: u32 = 0;\nconst CLOCK_PIN: u32 = 1;\nconst LATCH_PIN: u32 = 2;\nconst SPEED: u32 = 2;\n\nuse tock::{led, timer};\n\nfn push_one_bit(value: bool) {\n if value {\n led::on(DATA_PIN)\n } else {\n led::off(DATA_PIN)\n }\n led::on(CLOCK_PIN);\n timer::delay_ms(SPEED);\n led::off(CLOCK_PIN);\n timer::delay_ms(SPEED);\n}\n\nfn push_bits(values: &[bool]) {\n for i in values {\n push_one_bit(*i);\n }\n display();\n timer::delay_ms(200);\n}\n\nfn display() {\n led::on(LATCH_PIN);\n timer::delay_ms(SPEED);\n led::off(LATCH_PIN);\n}\n\nfn number_to_bits(n: u8) -> [bool; 8] {\n match n {\n 1 => [true, true, true, false, true, false, true, true],\n 2 => [false, true, false, false, true, true, false, false],\n 3 => [false, true, false, false, true, false, false, true],\n 4 => [false, false, true, false, true, false, true, true],\n 5 => [false, false, false, true, true, false, false, true],\n 6 => [false, false, false, true, true, false, false, false],\n 7 => [true, true, false, false, true, false, true, true],\n 8 => [false, false, false, false, true, false, false, false],\n 9 => [false, false, false, false, true, false, false, true],\n 0 => [true, false, false, false, true, false, false, false],\n _ => [true, true, true, true, false, true, true, true],\n }\n}\n\nfn main() {\n let mut i = 0;\n loop {\n i = (i + 1) % 11;\n push_bits(&number_to_bits(i));\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Test for a particular parallel codegen corner case\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// Tests parallel codegen - this can fail if the symbol for the anonymous\n// closure in `sum` pollutes the second codegen unit from the first.\n\n// compile-flags: -C codegen_units=2\n\n#![feature(core)]\n#![feature(iter_arith)]\n\nmod a {\n fn foo() {\n let x = [\"a\", \"bob\", \"c\"];\n let len: usize = x.iter().map(|s| s.len()).sum();\n }\n}\n\nmod b {\n fn bar() {\n let x = [\"a\", \"bob\", \"c\"];\n let len: usize = x.iter().map(|s| s.len()).sum();\n }\n}\n\nfn main() {\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a regression test for the const eval type resolution\n" }, { "from": "gpt", "value": "// Copyright 2017 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\ntrait Nat {\n const VALUE: usize;\n}\n\nstruct Zero;\nstruct Succ<N>(N);\n\nimpl Nat for Zero {\n const VALUE: usize = 0;\n}\n\nimpl<N: Nat> Nat for Succ<N> {\n const VALUE: usize = N::VALUE + 1;\n}\n\nfn main() {\n let x: [i32; <Succ<Succ<Succ<Succ<Zero>>>>>::VALUE] = [1, 2, 3, 4];\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add command for FLAC metdata\n\nFor now it only prints stream info\n" }, { "from": "gpt", "value": "extern crate docopt;\nextern crate flac;\nextern crate rustc_serialize;\n\nuse docopt::Docopt;\nuse flac::{ReadStream, Stream, StreamProducer};\n\nuse std::env;\nuse std::fs::File;\n\nconst USAGE: &'static str = \"\nUsage: metadata streaminfo <input>\n metadata --help\n\nOptions:\n -h, --help Show this message.\n\";\n\n#[derive(Debug, RustcDecodable)]\nstruct Arguments {\n arg_input: String,\n cmd_streaminfo: bool,\n}\n\nfn print_stream_info<P: StreamProducer>(stream: &Stream<P>) {\n let info = stream.info();\n\n println!(\"StreamInfo\n Minimum block size: {}\n Maximum block size: {}\n Maximum frame size: {}\n Maximum frame size: {}\n Sample rate: {} Hz\n Number of channels: {}\n Bits per sample: {}\n Total samples: {}\n MD5 sum: {:?}\",\n info.min_block_size, info.max_block_size,\n info.min_frame_size, info.max_frame_size,\n info.sample_rate, info.channels, info.bits_per_sample, info.total_samples,\n info.md5_sum);\n}\n\nfn main() {\n let args: Arguments = Docopt::new(USAGE)\n .and_then(|d| d.argv(env::args()).decode())\n .unwrap_or_else(|e| e.exit());\n\n let stream = Stream::<ReadStream<File>>::from_file(&args.arg_input)\n .expect(\"Couldn't parse file\");\n\n if args.cmd_streaminfo {\n print_stream_info(&stream);\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add day 25 part 1 solution\n" }, { "from": "gpt", "value": "// advent25.rs\n// copy protection code\n\n#[macro_use] extern crate scan_fmt;\n\nuse std::io;\n\nfn main() {\n let mut input = String::new();\n io::stdin().read_line(&mut input).ok().expect(\"Failed to read line\");\n let (row, col) = scan_fmt!(\n &input, \n \"To continue, please consult the code grid in the manual. Enter the code at row {}, column {}.\", \n u32, u32);\n\n println!(\"code = {}\", get_code(col.unwrap(), row.unwrap()));\n}\n\nfn get_triangular(x: u32) -> u32 {\n x * (x + 1) / 2\n}\n\nfn get_ordinal(x: u32, y: u32) -> u32 {\n x + get_triangular(x + y - 2)\n}\n\nfn get_code(x: u32, y: u32) -> u64 {\n const START_VAL: u64 = 20151125;\n const MULT_VAL: u64 = 252533;\n const MOD_VAL: u64 = 33554393;\n\n let mut val = START_VAL;\n\n for _ in 1..get_ordinal(x, y) {\n val = val * MULT_VAL % MOD_VAL;\n }\n\n val\n}\n\n#[test]\nfn test_get_ordinal() {\n assert_eq!(1, get_ordinal(1, 1));\n assert_eq!(2, get_ordinal(1, 2));\n assert_eq!(3, get_ordinal(2, 1));\n assert_eq!(4, get_ordinal(1, 3));\n assert_eq!(5, get_ordinal(2, 2));\n assert_eq!(18, get_ordinal(3, 4));\n assert_eq!(21, get_ordinal(6, 1));\n}\n\n#[test]\nfn test_get_code() {\n assert_eq!(20151125, get_code(1, 1));\n assert_eq!(77061, get_code(1, 5));\n assert_eq!(1534922, get_code(5, 6));\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add tests for macros hygiene\n" }, { "from": "gpt", "value": "#[test]\nfn iproduct_hygiene() {\n let _ = itertools::iproduct!(0..6);\n let _ = itertools::iproduct!(0..6, 0..9);\n let _ = itertools::iproduct!(0..6, 0..9, 0..12);\n}\n\n#[test]\nfn izip_hygiene() {\n let _ = itertools::izip!(0..6);\n let _ = itertools::izip!(0..6, 0..9);\n let _ = itertools::izip!(0..6, 0..9, 0..12);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add Rust solution for bubblesort\n" }, { "from": "gpt", "value": "use std::cmp::PartialOrd;\n\n/// An in-place implementation of bubble sort\nfn bubble_sort<T>(arr: &mut [T])\nwhere T: PartialOrd {\n for i in 0..arr.len() {\n for j in i..arr.len() {\n if arr[i] > arr[j] {\n arr.swap(i, j);\n }\n }\n }\n}\n\nfn main() {\n let arr = &mut [5,4,1,2,3];\n bubble_sort(arr);\n assert_eq!(&[1,2,3,4,5], arr);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a simple decoder benchmark\n" }, { "from": "gpt", "value": "#![feature(test)]\nextern crate test;\nextern crate rosc;\n\nuse self::test::Bencher;\n\n#[bench]\nfn bench_decode(b: &mut Bencher) {\n // The message was captured from the `ytterbium` lemur patch looks like this:\n // OSC Bundle: OscBundle { timetag: Time(0, 1), content: [Message(OscMessage { addr: \"/OSCILLATORS/OSC2/ADSR/x\", args: Some([Float(0.1234567), Float(0.1234567), Float(0.1234567), Float(0.1234567)]) })] }\n let raw_msg: [u8; 72] = [35, 98, 117, 110, 100, 108, 101, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n 52, 47, 79, 83, 67, 73, 76, 76, 65, 84, 79, 82, 83, 47, 79, 83, 67,\n 50, 47, 65, 68, 83, 82, 47, 122, 0, 0, 0, 0, 44, 102, 102, 102, 102,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n b.iter(|| rosc::decoder::decode(&raw_msg).unwrap());\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test to deserialize unsigned int\n\nSigned-off-by: Matthias Beyer <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@beyermatthias.de>\n" }, { "from": "gpt", "value": "#![cfg(feature = \"preserve_order\")]\n\nextern crate indexmap;\n\n#[derive(serde::Deserialize, Eq, PartialEq, Debug)]\nstruct Container<T> {\n inner: T,\n}\n\n#[derive(serde::Deserialize, Eq, PartialEq, Debug)]\nstruct Unsigned {\n unsigned: u16,\n}\n\nimpl Default for Unsigned {\n fn default() -> Self {\n Self { unsigned: 128 }\n }\n}\n\nimpl From<Unsigned> for config::ValueKind {\n fn from(unsigned: Unsigned) -> Self {\n let mut properties = indexmap::IndexMap::new();\n properties.insert(\n \"unsigned\".to_string(),\n config::Value::from(unsigned.unsigned),\n );\n\n Self::Table(properties)\n }\n}\n\n#[test]\nfn test_deser_unsigned_int() {\n let container = Container {\n inner: Unsigned::default(),\n };\n\n let built = config::Config::builder()\n .set_default(\"inner\", Unsigned::default())\n .unwrap()\n .build()\n .unwrap()\n .try_deserialize::<Container<Unsigned>>()\n .unwrap();\n\n assert_eq!(container, built);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for Command::current_dir behavior.\n" }, { "from": "gpt", "value": "// run-pass\n// ignore-emscripten no processes\n// ignore-sgx no processes\n\nuse std::env;\nuse std::fs;\nuse std::path::Path;\nuse std::process::Command;\n\nfn main() {\n // Checks the behavior of current_dir when used with a relative exe path.\n let me = env::current_exe().unwrap();\n if matches!(env::args().skip(1).next().as_deref(), Some(\"current-dir\")) {\n let cwd = env::current_dir().unwrap();\n assert_eq!(cwd.file_name().unwrap(), \"bar\");\n std::process::exit(0);\n }\n let exe = me.file_name().unwrap();\n let cwd = std::env::current_dir().unwrap();\n eprintln!(\"cwd={:?}\", cwd);\n let foo = cwd.join(\"foo\");\n let bar = cwd.join(\"bar\");\n fs::create_dir_all(&foo).unwrap();\n fs::create_dir_all(&bar).unwrap();\n fs::copy(&me, foo.join(exe)).unwrap();\n\n // Unfortunately this is inconsistent based on the platform, see\n // https://github.com/rust-lang/rust/issues/37868. On Windows,\n // it is relative *before* changing the directory, and on Unix\n // it is *after* changing the directory.\n let relative_exe = if cfg!(windows) {\n Path::new(\"foo\").join(exe)\n } else {\n Path::new(\"../foo\").join(exe)\n };\n\n let status = Command::new(relative_exe)\n .arg(\"current-dir\")\n .current_dir(\"bar\")\n .status()\n .unwrap();\n assert!(status.success());\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add some XML character predicates\n" }, { "from": "gpt", "value": "use super::{Document,Root,RootChild};\n\ntrait XmlChar {\n fn is_name_start_char(&self) -> bool;\n fn is_name_char(&self) -> bool;\n}\n\nimpl XmlChar for char {\n fn is_name_start_char(&self) -> bool {\n match *self {\n ':' |\n 'A'..'Z' |\n '_' |\n 'a'..'z' |\n '\\U000000C0'..'\\U000000D6' |\n '\\U000000D8'..'\\U000000F6' |\n '\\U000000F8'..'\\U000002FF' |\n '\\U00000370'..'\\U0000037D' |\n '\\U0000037F'..'\\U00001FFF' |\n '\\U0000200C'..'\\U0000200D' |\n '\\U00002070'..'\\U0000218F' |\n '\\U00002C00'..'\\U00002FEF' |\n '\\U00003001'..'\\U0000D7FF' |\n '\\U0000F900'..'\\U0000FDCF' |\n '\\U0000FDF0'..'\\U0000FFFD' |\n '\\U00010000'..'\\U000EFFFF' => true,\n _ => false,\n }\n }\n\n fn is_name_char(&self) -> bool {\n if self.is_name_start_char() { return true; }\n match *self {\n '-' |\n '.' |\n '0'..'9' |\n '\\u00B7' |\n '\\u0300'..'\\u036F' |\n '\\u203F'..'\\u2040' => true,\n _ => false\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for associated const version display\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// ignore-tidy-linelength\n\n#![crate_name = \"foo\"]\n\n#![feature(staged_api)]\n\n#![stable(since=\"1.1.1\", feature=\"rust1\")]\n\n#[stable(since=\"1.1.1\", feature=\"rust1\")]\npub struct SomeStruct;\n\nimpl SomeStruct {\n // @has 'foo/struct.SomeStruct.html' '//*[@id=\"SOME_CONST.v\"]//div[@class=\"since\"]' '1.1.2'\n #[stable(since=\"1.1.2\", feature=\"rust2\")]\n pub const SOME_CONST: usize = 0;\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add regression test for atomics being Send + Sync\n\nThanks to Tamir Duberstein for the implementation suggestion.\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// pretty-expanded FIXME #23616\n\nuse std::sync::atomic::*;\n\ntrait SendSync: Send + Sync {}\n\nimpl SendSync for AtomicBool {}\nimpl SendSync for AtomicIsize {}\nimpl SendSync for AtomicUsize {}\nimpl<T> SendSync for AtomicPtr<T> {}\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for --remap-path-prefix on std imports\n" }, { "from": "gpt", "value": "// ignore-windows\n\n// compile-flags: -g -C no-prepopulate-passes --remap-path-prefix=/=/the/root/\n\n// Here we check that imported code from std has their path remapped\n\n// CHECK: !DIFile(filename: \"{{/the/root/.*/library/std/src/panic.rs}}\"\nfn main() {\n std::thread::spawn(|| {\n println!(\"hello\");\n });\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add solution to problem 37\n" }, { "from": "gpt", "value": "#![feature(core)]\n#[macro_use] extern crate libeuler;\nextern crate num;\n\nuse libeuler::SieveOfAtkin;\nuse num::traits::PrimInt;\n\n/// The number 3797 has an interesting property. Being prime itself, it is possible to continuously\n/// remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7.\n/// Similarly we can work from right to left: 3797, 379, 37, and 3.\n///\n/// Find the sum of the only eleven primes that are both truncatable from left to right and right\n/// to left.\n///\n/// NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.\nfn main() {\n solutions! {\n sol naive {\n let sieve = SieveOfAtkin::new(1_000_000);\n sieve.iter().filter(|s| truncable(s, &sieve)).sum::<u64>()\n }\n }\n}\n\nfn truncable(i: &u64, sieve: &SieveOfAtkin) -> bool {\n if *i < 10 { return false }\n\n let mut a = i / 10;\n let mut digits = 1;\n\n while a > 0 {\n digits += 1;\n\n if !sieve.is_prime(a) {\n return false;\n }\n\n a /= 10;\n }\n\n let mut b = i.clone();\n for d in 0..(digits-1) {\n let pow = 10.pow(digits - d - 1);\n let dig = b / pow * pow;\n b -= dig;\n\n if !sieve.is_prime(b) {\n return false;\n }\n }\n\n true\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add temporary parser for /proc/sys/fs/file-max\n" }, { "from": "gpt", "value": "// NOTE: I'll open a PR on procinfo-rs to parse /proc/sys/fs/file-max\n// in the meantime, I wrote it here\n// Arnaud Lefebvre - 23/02/17\n\nuse std::fs::File;\nuse std::io::{Read, Error, ErrorKind};\n\nstatic FILE_MAX_PATH: &'static str = \"/proc/sys/fs/file-max\";\n\n// kernel uses get_max_files which returns a unsigned long\n// see include/linux/fs.h\npub fn limits_file_max() -> Result<usize, Error> {\n let mut buf = String::new();\n let mut file = try!(File::open(FILE_MAX_PATH));\n try!(file.read_to_string(&mut buf));\n buf.trim().parse::<usize>().or(Err(Error::new(ErrorKind::InvalidInput, format!(\"Couldn't parse {} value into usize\", FILE_MAX_PATH))))\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test for error_on_line_overflow_strings\n" }, { "from": "gpt", "value": "// rustfmt-error_on_line_overflow_strings: false\n// Suppress an error on line overflow strings.\n\nfn main() {\n let x = \" \";\n let a = \"\n \n\";\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add failing use case for CubeMapArray type in shaders.\n\nThis is because of missing UniformType mapping.\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate glium;\n\nmod support;\n\n// Tests for support of the cube map array type in programs.\nfn program_support_for_cube_map_array(type_prefix: &str) {\n let display = support::build_display();\n let _ = glium::Program::from_source(\n &display,\n \"\n #version 400\n\n attribute vec2 position;\n\n void main() {\n gl_Position = vec4(position, 0.0, 1.0);\n }\n \",\n &format!(\n \"\n #version 400\n\n uniform {}samplerCubeArray cube_textures;\n\n void main() {{\n gl_FragColor = texture(cube_textures, vec4(0, 0, 0, 0));\n }}\n \",\n type_prefix\n ),\n None\n ).unwrap();\n}\n\n#[test]\nfn program_support_for_cube_map_array_float() {\n program_support_for_cube_map_array(\"\");\n}\n\n#[test]\nfn program_support_for_cube_map_array_unsigned() {\n program_support_for_cube_map_array(\"u\");\n}\n\n#[test]\nfn program_support_for_cube_map_array_integral() {\n program_support_for_cube_map_array(\"i\");\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add simple vertex buffer tests\n\ncc #15\n" }, { "from": "gpt", "value": "#![feature(phase)]\n\n#[phase(plugin)]\nextern crate glium_macros;\n\nextern crate glutin;\nextern crate glium;\n\nuse glium::DisplayBuild;\n\n#[test]\nfn vertex_buffer_creation() {\n #[vertex_format]\n #[allow(dead_code)]\n struct Vertex {\n field1: [f32, ..3],\n field2: [f32, ..3],\n }\n\n let display = glutin::HeadlessRendererBuilder::new(1024, 768)\n .build_glium().unwrap();\n\n glium::VertexBuffer::new(&display, \n vec![\n Vertex { field1: [-0.5, -0.5, 0.0], field2: [0.0, 1.0, 0.0] },\n Vertex { field1: [ 0.0, 0.5, 1.0], field2: [0.0, 0.0, 1.0] },\n Vertex { field1: [ 0.5, -0.5, 0.0], field2: [1.0, 0.0, 0.0] },\n ]\n );\n}\n\n#[test]\nfn vertex_buffer_mapping_read() {\n #[vertex_format]\n struct Vertex {\n field1: [u8, ..2],\n field2: [u8, ..2],\n }\n\n let display = glutin::HeadlessRendererBuilder::new(1024, 768)\n .build_glium().unwrap();\n\n let mut vb = glium::VertexBuffer::new(&display, \n vec![\n Vertex { field1: [ 2, 3], field2: [ 5, 7] },\n Vertex { field1: [12, 13], field2: [15, 17] },\n ]\n );\n\n let mapping = vb.map();\n assert_eq!(mapping[0].field1.as_slice(), [2, 3].as_slice());\n assert_eq!(mapping[1].field2.as_slice(), [15, 17].as_slice());\n}\n\n#[test]\nfn vertex_buffer_mapping_write() {\n #[vertex_format]\n struct Vertex {\n field1: [u8, ..2],\n field2: [u8, ..2],\n }\n\n let display = glutin::HeadlessRendererBuilder::new(1024, 768)\n .build_glium().unwrap();\n\n let mut vb = glium::VertexBuffer::new(&display, \n vec![\n Vertex { field1: [ 2, 3], field2: [ 5, 7] },\n Vertex { field1: [12, 13], field2: [15, 17] },\n ]\n );\n\n {\n let mut mapping = vb.map();\n mapping[0].field1 = [0, 1];\n }\n\n let mapping = vb.map();\n assert_eq!(mapping[0].field1.as_slice(), [0, 1].as_slice());\n assert_eq!(mapping[1].field2.as_slice(), [15, 17].as_slice());\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add syntactic test for rest patterns.\n" }, { "from": "gpt", "value": "// Here we test that `..` is allowed in all pattern locations *syntactically*.\n// The semantic test is in `rest-pat-semantic-disallowed.rs`.\n\n// check-pass\n\nfn main() {}\n\nmacro_rules! accept_pat {\n ($p:pat) => {}\n}\n\naccept_pat!(..);\n\n#[cfg(FALSE)]\nfn rest_patterns() {\n // Top level:\n fn foo(..: u8) {}\n let ..;\n\n // Box patterns:\n let box ..;\n\n // In or-patterns:\n match x {\n .. | .. => {}\n }\n\n // Ref patterns:\n let &..;\n let &mut ..;\n\n // Ident patterns:\n let x @ ..;\n let ref x @ ..;\n let ref mut x @ ..;\n\n // Tuple:\n let (..); // This is interpreted as a tuple pattern, not a parenthesis one.\n let (..,); // Allowing trailing comma.\n let (.., .., ..); // Duplicates also.\n let (.., P, ..); // Including with things in between.\n\n // Tuple struct (same idea as for tuple patterns):\n let A(..);\n let A(..,);\n let A(.., .., ..);\n let A(.., P, ..);\n\n // Array/Slice (like with tuple patterns):\n let [..];\n let [..,];\n let [.., .., ..];\n let [.., P, ..];\n\n // Random walk to guard against special casing:\n match x {\n .. |\n [\n (\n box ..,\n &(..),\n &mut ..,\n x @ ..\n ),\n ref x @ ..,\n ] |\n ref mut x @ ..\n => {}\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add codegen test to make sure that closures are 'internalized' properly.\n" }, { "from": "gpt", "value": "// Copyright 2016 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// compile-flags: -C no-prepopulate-passes\n\npub fn main() {\n\n // We want to make sure that closures get 'internal' linkage instead of\n // 'weak_odr' when they are not shared between codegen units\n // CHECK: define internal {{.*}}_ZN20internalize_closures4main{{.*}}$u7b$$u7b$closure$u7d$$u7d$\n let c = |x:i32| { x + 1 };\n let _ = c(1);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for duplicate definitions of structs and enum struct variants.\n" }, { "from": "gpt", "value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nenum Foo { C { a: int, b: int } }\nstruct C { a: int, b: int } //~ ERROR error: duplicate definition of type `C`\n\nstruct A { x: int }\nenum Bar { A { x: int } } //~ ERROR error: duplicate definition of type `A`\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a missing file that defines the `Unit` type.\n" }, { "from": "gpt", "value": "use traits::geometry::Norm;\n\n\n/// A wrapper that ensures the undelying algebraic entity has a unit norm.\n#[repr(C)]\n#[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)]\npub struct Unit<T> {\n v: T\n}\n\nimpl<T: Norm> Unit<T> {\n /// Normalize the given value and return it wrapped on a `Unit` structure.\n #[inline]\n pub fn new(v: &T) -> Self {\n Unit { v: v.normalize() }\n }\n\n /// Attempts to normalize the given value and return it wrapped on a `Unit` structure.\n ///\n /// Returns `None` if the norm was smaller or equal to `min_norm`.\n #[inline]\n pub fn try_new(v: &T, min_norm: T::NormType) -> Option<Self> {\n v.try_normalize(min_norm).map(|v| Unit { v: v })\n }\n\n /// Normalize the given value and return it wrapped on a `Unit` structure and its norm.\n #[inline]\n pub fn new_and_get(mut v: T) -> (Self, T::NormType) {\n let n = v.normalize_mut();\n\n (Unit { v: v }, n)\n }\n\n /// Normalize the given value and return it wrapped on a `Unit` structure and its norm.\n ///\n /// Returns `None` if the norm was smaller or equal to `min_norm`.\n #[inline]\n pub fn try_new_and_get(mut v: T, min_norm: T::NormType) -> Option<(Self, T::NormType)> {\n if let Some(n) = v.try_normalize_mut(min_norm) {\n Some((Unit { v: v }, n))\n }\n else {\n None\n }\n }\n\n /// Normalizes this value again. This is useful when repeated computations \n /// might cause a drift in the norm because of float inaccuracies.\n ///\n /// Returns the norm beform re-normalization (should be close to `1.0`).\n #[inline]\n pub fn renormalize(&mut self) -> T::NormType {\n self.v.normalize_mut()\n }\n}\n\nimpl<T> Unit<T> {\n /// Wraps the given value, assuming it is already normalized.\n ///\n /// This function is not safe because `v` is not verified to be actually normalized.\n #[inline]\n pub fn from_unit_value_unchecked(v: T) -> Self {\n Unit { v: v }\n }\n\n /// Retrieves the underlying value.\n #[inline]\n pub fn unwrap(self) -> T {\n self.v\n }\n}\n\nimpl<T> AsRef<T> for Unit<T> {\n #[inline]\n fn as_ref(&self) -> &T {\n &self.v\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add exercise 6.5 - strftime\n" }, { "from": "gpt", "value": "/// Exercise: Write a program to obtain the current time and print it using strftime,\n/// so that it looks like the default output from date(1). Set the TZ environment\n/// variable to different values and see what happens.\n\nextern crate libc;\n#[macro_use(cstr)]\nextern crate apue;\n\nuse libc::{tm, time_t, c_char, size_t, printf};\nuse std::mem::uninitialized;\n\nextern \"C\" {\n fn time(time: *mut time_t) -> time_t;\n fn localtime(time: *const time_t) -> *mut tm;\n fn strftime(s: *mut c_char,\n maxsize: size_t,\n format: *const c_char,\n timeptr: *const tm)\n -> size_t;\n}\n\nfn main() {\n unsafe {\n let mut buf: [c_char; 256] = uninitialized();\n let mut t: time_t = uninitialized();\n time(&mut t);\n strftime(buf.as_mut_ptr(),\n 256,\n cstr!(\"%a %b %e %H:%M:%S %Z %Y\"),\n localtime(&t));\n printf(cstr!(\"%s\\n\"), buf.as_ptr());\n }\n}\n\n// ## Results\n//\n// $ export TZ='Europe/Zurich'\n// $ macos/target/debug/e05-strftime\n// Sun Oct 2 14:59:33 CEST 2016\n//\n// $ export TZ='America/Toronto'\n// $ macos/target/debug/e05-strftime\n// Sun Oct 2 09:00:50 EDT 2016\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test demonstrating context inference failure\n" }, { "from": "gpt", "value": "use anyhow::{Context, Result};\n\n// https://github.com/dtolnay/anyhow/issues/18\n#[test]\nfn test_inference() -> Result<()> {\n let x = \"1\";\n let y: u32 = x.parse().context(\"...\")?;\n assert_eq!(y, 1);\n Ok(())\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Create an example for the client module.\n" }, { "from": "gpt", "value": "// Copyright 2020 Google LLC\n//\n// Use of this source code is governed by an MIT-style license that can be found\n// in the LICENSE file or at https://opensource.org/licenses/MIT.\n\nfn main() -> std::io::Result<()> {\n fleetspeak::client::startup(\"0.0.1\")?;\n\n loop {\n let request = fleetspeak::client::receive::<String>()?;\n let response = format!(\"Hello {}!\", request);\n fleetspeak::client::send(\"greeter\", \"greeting\", response)?;\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test for deprecated phase(syntax)\n" }, { "from": "gpt", "value": "// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(phase)]\n\n//~ WARNING phase(syntax) is a deprecated synonym for phase(plugin)\n#[phase(syntax, link)]\nextern crate log;\n\nfn main() {\n debug!(\"foo\");\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add rustdoc regression test for the unused_braces lint\n" }, { "from": "gpt", "value": "// check-pass\n\n// This tests the bug in #70814, where the unused_braces lint triggered on the following code\n// without providing a span.\n\n#![deny(unused_braces)]\n\nfn main() {\n {\n {\n use std;\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a simple trait for single time parsing\n\nThis is inspired by the chomp project <https://github.com/m4rw3r/chomp>.\n" }, { "from": "gpt", "value": "use nom::IResult;\n\npub trait StreamProducer {\n fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>\n where F: FnOnce(&[u8]) -> IResult<&[u8], T>;\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a compile-fail test for attempts to extend non-objects.\n" }, { "from": "gpt", "value": "//error-pattern:x does not have object type\nuse std;\n\nfn main() {\n auto x = 3;\n\n auto anon_obj = obj {\n fn foo() -> int {\n ret 3;\n }\n with x\n };\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add EntryHeader type for store\n" }, { "from": "gpt", "value": "use toml::Table;\n\npub struct EntryHeader {\n toml: Table,\n}\n\nimpl EntryHeader {\n\n pub fn new(toml: Table) -> EntryHeader {\n EntryHeader {\n toml: toml,\n }\n }\n\n pub fn toml(&self) -> &Table {\n &self.toml\n }\n\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for associated constants in the sidebar\n" }, { "from": "gpt", "value": "#![crate_name = \"foo\"]\n\npub trait Trait {\n const FOO: u32 = 12;\n\n fn foo();\n}\n\npub struct Bar;\n\n// @has 'foo/struct.Bar.html'\n// @has - '//h3[@class=\"sidebar-title\"]' 'Associated Constants'\n// @has - '//div[@class=\"sidebar-elems\"]//div[@class=\"sidebar-links\"]/a' 'FOO'\nimpl Trait for Bar {\n const FOO: u32 = 1;\n\n fn foo() {}\n}\n\npub enum Foo {\n A,\n}\n\n// @has 'foo/enum.Foo.html'\n// @has - '//h3[@class=\"sidebar-title\"]' 'Associated Constants'\n// @has - '//div[@class=\"sidebar-elems\"]//div[@class=\"sidebar-links\"]/a' 'FOO'\nimpl Trait for Foo {\n const FOO: u32 = 1;\n\n fn foo() {}\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "test: Fix depcrecated alias for int\n" }, { "from": "human", "value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\ntrait U { fn f(self); }\nimpl U for int { fn f(self) {} }\npub fn main() { 4.f(); }\n" }, { "from": "gpt", "value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\ntrait U { fn f(self); }\nimpl U for isize { fn f(self) {} }\npub fn main() { 4.f(); }\n" } ]
rust
chosen
[ { "from": "human", "value": "test: Add a test for trait inheritance with self as a type parameter. rs=test-only\n" }, { "from": "gpt", "value": "trait Foo<T> {\n fn f(&self, x: &T);\n}\n\ntrait Bar : Foo<self> {\n fn g(&self);\n}\n\nstruct S {\n x: int\n}\n\nimpl S : Foo<S> {\n fn f(&self, x: &S) {\n io::println(x.x.to_str());\n }\n}\n\nimpl S : Bar {\n fn g(&self) {\n self.f(self);\n }\n}\n\nfn main() {\n let s = S { x: 1 };\n s.g();\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for `Ipv6Addr` methods in a const context\n" }, { "from": "gpt", "value": "// run-pass\n\n#![feature(ip)]\n#![feature(const_ipv6)]\n\nuse std::net::{Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};\n\nfn main() {\n const IP_ADDRESS : Ipv6Addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);\n assert_eq!(IP_ADDRESS, Ipv6Addr::LOCALHOST);\n\n const SEGMENTS : [u16; 8] = IP_ADDRESS.segments();\n assert_eq!(SEGMENTS, [0 ,0 ,0 ,0 ,0 ,0 ,0, 1]);\n\n const OCTETS : [u8; 16] = IP_ADDRESS.octets();\n assert_eq!(OCTETS, [0 ,0 ,0 ,0 ,0 ,0 ,0, 0 ,0 ,0 ,0 ,0 ,0 ,0, 0, 1]);\n\n const IS_UNSPECIFIED : bool = IP_ADDRESS.is_unspecified();\n assert!(!IS_UNSPECIFIED);\n\n const IS_LOOPBACK : bool = IP_ADDRESS.is_loopback();\n assert!(IS_LOOPBACK);\n\n const IS_GLOBAL : bool = IP_ADDRESS.is_global();\n assert!(!IS_GLOBAL);\n\n const IS_UNIQUE_LOCAL : bool = IP_ADDRESS.is_unique_local();\n assert!(!IS_UNIQUE_LOCAL);\n\n const IS_UNICAST_LINK_LOCAL_STRICT : bool = IP_ADDRESS.is_unicast_link_local_strict();\n assert!(!IS_UNICAST_LINK_LOCAL_STRICT);\n\n const IS_UNICAST_LINK_LOCAL : bool = IP_ADDRESS.is_unicast_link_local();\n assert!(!IS_UNICAST_LINK_LOCAL);\n\n const IS_UNICAST_SITE_LOCAL : bool = IP_ADDRESS.is_unicast_site_local();\n assert!(!IS_UNICAST_SITE_LOCAL);\n\n const IS_DOCUMENTATION : bool = IP_ADDRESS.is_documentation();\n assert!(!IS_DOCUMENTATION);\n\n const IS_UNICAST_GLOBAL : bool = IP_ADDRESS.is_unicast_global();\n assert!(!IS_UNICAST_GLOBAL);\n\n const MULTICAST_SCOPE : Option<Ipv6MulticastScope> = IP_ADDRESS.multicast_scope();\n assert_eq!(MULTICAST_SCOPE, None);\n\n const IS_MULTICAST : bool = IP_ADDRESS.is_multicast();\n assert!(!IS_MULTICAST);\n\n const IP_V4 : Option<Ipv4Addr> = IP_ADDRESS.to_ipv4();\n assert_eq!(IP_V4.unwrap(), Ipv4Addr::new(0, 0, 0, 1));\n}" } ]
rust
chosen
[ { "from": "human", "value": "Solve Simple Sum in rust\n" }, { "from": "gpt", "value": "use std::io;\n\nfn main() {\n let mut input_a = String::new();\n let mut input_b = String::new();\n\n if let Err(_e) = io::stdin().read_line(&mut input_a){}\n if let Err(_e) = io::stdin().read_line(&mut input_b){}\n\n let a: i32 = input_a.trim().parse().unwrap();\n let b: i32 = input_b.trim().parse().unwrap();\n\n println!(\"SOMA = {}\", a + b);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add simpler, but less performant decode example\n" }, { "from": "gpt", "value": "// Claxon -- A FLAC decoding library in Rust\n// Copyright 2017 Ruud van Asseldonk\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// A copy of the License has been included in the root of the repository.\n\n// This file contains a minimal example of using Claxon and Hound to decode a\n// flac file. This can be done more efficiently, but it is also more verbose.\n// See the `decode` example for that.\n\nextern crate claxon;\nextern crate hound;\n\nuse std::env;\nuse std::path::Path;\n\nfn decode_file(fname: &Path) {\n let mut reader = claxon::FlacReader::open(fname).expect(\"failed to open FLAC stream\");\n\n let spec = hound::WavSpec {\n channels: reader.streaminfo().channels as u16,\n sample_rate: reader.streaminfo().sample_rate,\n bits_per_sample: reader.streaminfo().bits_per_sample as u16,\n sample_format: hound::SampleFormat::Int,\n };\n\n let fname_wav = fname.with_extension(\"wav\");\n let opt_wav_writer = hound::WavWriter::create(fname_wav, spec);\n let mut wav_writer = opt_wav_writer.expect(\"failed to create wav file\");\n\n for opt_sample in reader.samples() {\n let sample = opt_sample.expect(\"failed to decode FLAC stream\");\n wav_writer.write_sample(sample).expect(\"failed to write wav file\");\n }\n\n wav_writer.finalize().expect(\"failed to finalize wav file\");\n}\n\nfn main() {\n for fname in env::args().skip(1) {\n decode_file(&Path::new(&fname));\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add an xfailed test for bogus deep copying of things containing resources\n" }, { "from": "gpt", "value": "// xfail-test\n// expected error: mismatched kinds\n\nresource r(i: @mutable int) {\n *i = *i + 1;\n}\n\nfn main() {\n let i = @mutable 0;\n {\n // Can't do this copy\n let x = ~~~{y: r(i)};\n let z = x;\n }\n log_err *i;\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add test for E0152 error message improvement\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// Test for issue #31788\n\n// error-pattern: duplicate entry for `panic_fmt`, first definition found in `std`\n\n#![feature(lang_items)]\n\n#[lang = \"panic_fmt\"]\nfn panic_fmt() -> ! {\n loop {}\n}\n\nfn main() {}" } ]
rust
chosen
[ { "from": "human", "value": "Add test for ICE 6793\n" }, { "from": "gpt", "value": "//! This is a reproducer for the ICE 6793: https://github.com/rust-lang/rust-clippy/issues/6793.\n//! The ICE is caused by using `TyCtxt::type_of(assoc_type_id)`, which is the same as the ICE 6792.\n\ntrait Trait {\n type Ty: 'static + Clone;\n\n fn broken() -> Self::Ty;\n}\n\n#[derive(Clone)]\nstruct MyType {\n x: i32,\n}\n\nimpl Trait for MyType {\n type Ty = MyType;\n\n fn broken() -> Self::Ty {\n Self::Ty { x: 1 }\n }\n}\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a wrapper for C file descriptors\n" }, { "from": "gpt", "value": "extern crate libc;\nuse self::libc::{c_int, close};\nuse std::fmt;\n\n\npub struct CFileDescriptor {\n fd: c_int\n}\n\n\nimpl CFileDescriptor {\n pub fn new(fd: c_int) -> CFileDescriptor {\n CFileDescriptor {fd: fd}\n }\n}\n\n\nimpl Drop for CFileDescriptor {\n fn drop(&mut self) {\n let result = unsafe {\n close(self.fd)\n };\n\n // There isn't much we can do if this failed\n if result != 0 {\n println!(\"Warning: failed to close file descriptor when dropping\");\n }\n }\n}\n\n\nimpl fmt::Show for CFileDescriptor {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"<C File Descriptor {}>\", self.fd)\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "[Bonsai] Add the AST (missing file).\n" }, { "from": "gpt", "value": "// Copyright 2016 Pierre Talbot (IRCAM)\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n// http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npub type Program = Vec<Item>;\n\npub enum Item {\n Statement(Stmt),\n Fn(Function)\n}\n\npub type Block = Vec<Stmt>;\n\npub struct JavaTy {\n pub name: String,\n pub generics: Vec<JavaTy>\n}\n\npub struct Function {\n pub name: String,\n pub params: Vec<String>,\n pub body: Block\n}\n\npub enum Stmt {\n Par(Vec<Block>),\n Space(Vec<Block>),\n Let(LetDecl),\n LetInStore(LetInStoreDecl),\n When(EntailmentRel, Block),\n Pause,\n Trap(String, Block),\n Exit(String),\n Loop(Block),\n FnCall(String, Vec<String>),\n Tell(Var, Expr)\n}\n\npub struct LetDecl {\n pub transient: bool,\n pub var: String,\n pub var_ty: Option<JavaTy>,\n pub spacetime: Spacetime,\n pub expr: Expr\n}\n\npub struct LetInStoreDecl {\n pub location: String,\n pub loc_ty: Option<JavaTy>,\n pub store: String,\n pub expr: Expr\n}\n\npub struct EntailmentRel {\n pub left: StreamVar,\n pub right: Expr\n}\n\npub struct Var {\n pub name: String,\n pub args: Vec<Var>\n}\n\npub struct StreamVar {\n pub name: String,\n pub past: usize,\n pub args: Vec<StreamVar>\n}\n\npub enum Spacetime {\n SingleSpace,\n SingleTime,\n WorldLine,\n Location(String)\n}\n\npub enum Expr {\n JavaNew(JavaTy, Vec<Expr>),\n JavaObjectCall(String, Vec<JavaCall>),\n Number(u64),\n StringLiteral(String),\n Variable(StreamVar)\n}\n\npub struct JavaCall {\n pub property: String, // can be an attribute or a method.\n pub args: Vec<Expr>\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Test for cast causing static promotion failure.\n\nThis commit adds a test that ensures that a cast in a static doesn't\nstop const promotion within the static.\n" }, { "from": "gpt", "value": "// Copyright 2017 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(nll)]\n\n// run-pass\n\nstruct Slice(&'static [&'static [u8]]);\n\nstatic MAP: Slice = Slice(&[\n b\"CloseEvent\" as &'static [u8],\n]);\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add simple test of assert_eq!.\n" }, { "from": "human", "value": "#![feature(custom_attribute, box_syntax)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn rc_cell() -> i32 {\n use std::rc::Rc;\n use std::cell::Cell;\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r.get()\n}\n\n#[miri_run]\nfn arc() -> i32 {\n use std::sync::Arc;\n let a = Arc::new(42);\n *a\n}\n" }, { "from": "gpt", "value": "#![feature(custom_attribute, box_syntax)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn rc_cell() -> i32 {\n use std::rc::Rc;\n use std::cell::Cell;\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r.get()\n}\n\n#[miri_run]\nfn arc() -> i32 {\n use std::sync::Arc;\n let a = Arc::new(42);\n *a\n}\n\n#[miri_run]\nfn true_assert() {\n assert_eq!(1, 1);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Test that NRVO elides the call to `memcpy`\n" }, { "from": "gpt", "value": "// compile-flags: -O\n\n#![crate_type = \"lib\"]\n\n// Ensure that we do not call `memcpy` for the following function.\n// `memset` and `init` should be called directly on the return pointer.\n#[no_mangle]\npub fn nrvo(init: fn(&mut [u8; 4096])) -> [u8; 4096] {\n // CHECK-LABEL: nrvo\n // CHECK: @llvm.memset\n // CHECK-NOT: @llvm.memcpy\n // CHECK: ret\n // CHECK-EMPTY\n let mut buf = [0; 4096];\n init(&mut buf);\n buf\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix unit test that was illegally mutating an upvar\n" }, { "from": "human", "value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(overloaded_calls, unboxed_closures)]\n\n// Test by-ref capture of environment in unboxed closure types\n\nfn call_fn<F: Fn()>(f: F) {\n f()\n}\n\nfn call_fn_mut<F: FnMut()>(mut f: F) {\n f()\n}\n\nfn call_fn_once<F: FnOnce()>(f: F) {\n f()\n}\n\nfn main() {\n let mut x = 0u;\n let y = 2u;\n\n call_fn(|&:| x += y);\n call_fn_mut(|&mut:| x += y);\n call_fn_once(|:| x += y);\n assert_eq!(x, y * 3);\n}\n" }, { "from": "gpt", "value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(overloaded_calls, unboxed_closures)]\n\n// Test by-ref capture of environment in unboxed closure types\n\nfn call_fn<F: Fn()>(f: F) {\n f()\n}\n\nfn call_fn_mut<F: FnMut()>(mut f: F) {\n f()\n}\n\nfn call_fn_once<F: FnOnce()>(f: F) {\n f()\n}\n\nfn main() {\n let mut x = 0u;\n let y = 2u;\n\n call_fn(|&:| assert_eq!(x, 0));\n call_fn_mut(|&mut:| x += y);\n call_fn_once(|:| x += y);\n assert_eq!(x, y * 2);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Simplify `DSDT::new()` with fewer `unsafe` blocks\n" }, { "from": "human", "value": "use super::SDTHeader;\n\n#[repr(packed)]\n#[derive(Clone, Copy, Debug, Default)]\npub struct DSDT {\n pub header: SDTHeader,\n pub data: &'static [u8]\n\n}\n\nimpl DSDT {\n pub fn new(header: *const SDTHeader) -> Option<Self> {\n if unsafe { (*header).valid(\"DSDT\") } {\n Some(DSDT {\n header: unsafe { *header },\n data: unsafe { (*header).data() }\n })\n } else {\n None\n }\n }\n}\n" }, { "from": "gpt", "value": "use super::SDTHeader;\n\n#[repr(packed)]\n#[derive(Clone, Copy, Debug, Default)]\npub struct DSDT {\n pub header: SDTHeader,\n pub data: &'static [u8]\n\n}\n\nimpl DSDT {\n pub fn new(header: *const SDTHeader) -> Option<Self> {\n let header = unsafe { *header };\n if header.valid(\"DSDT\") {\n Some(DSDT {\n header: header,\n data: header.data(),\n })\n } else {\n None\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test to ensure edge-triggering\n" }, { "from": "gpt", "value": "/// Ensure all sockets operate on edge trigger mode.\n\nextern crate amy;\n\nuse std::net::{TcpListener, TcpStream};\nuse std::thread;\nuse std::str;\nuse std::io::{Read, Write};\n\nuse amy::{\n Poller,\n Event,\n};\n\nconst IP: &'static str = \"127.0.0.1:10008\";\n\n/// This test ensures that only one write event is received, even if no data is written. On a level\n/// triggered system, write events would come on every poll.\n#[test]\nfn edge_trigger() {\n\n // Spawn a listening thread and accept one connection\n thread::spawn(|| {\n let listener = TcpListener::bind(IP).unwrap();\n let (mut sock, _) = listener.accept().unwrap();\n // When the test completes, the client will send a \"stop\" message to shutdown the server.\n let mut buf = String::new();\n sock.read_to_string(&mut buf).unwrap();\n });\n\n // Setup a client socket in non-blocking mode\n // Loop until we connect because the listener needs to start first\n let mut sock;\n loop {\n if let Ok(s) = TcpStream::connect(IP) {\n sock = s;\n break;\n }\n }\n sock.set_nonblocking(true).unwrap();\n\n // Create the poller and registrar\n let mut poller = Poller::new().unwrap();\n let registrar = poller.get_registrar();\n\n // The socket should become writable once it's connected\n let id = registrar.register(&sock, Event::Write).unwrap();\n let notifications = poller.wait(250).unwrap();\n assert_eq!(1, notifications.len());\n assert_eq!(id, notifications[0].id);\n assert_eq!(Event::Write, notifications[0].event);\n\n // Poll as second time. There should be no notification, since the socket is edge triggered.\n let notifications = poller.wait(250).unwrap();\n assert_eq!(0, notifications.len());\n\n // Tell the listening thread to stop itself\n sock.write(\"stop\".as_bytes()).unwrap();\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add an XFAILed test for failing destructors\n\nIssue #236\n" }, { "from": "gpt", "value": "// error-pattern:fail\n// xfail-test\n\nresource r(i: int) {\n // What happens when destructors throw?\n fail;\n}\n\nfn main() {\n @0;\n let r <- r(0);\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add Showcase program to test and demonstrate the library\n" }, { "from": "gpt", "value": "/* Copyright 2016 Jordan Miner\n *\n * Licensed under the MIT license <LICENSE or\n * http://opensource.org/licenses/MIT>. This file may not be copied,\n * modified, or distributed except according to those terms.\n */\n\n#[macro_use]\nextern crate clear_coat;\nextern crate iup_sys;\nuse iup_sys::*;\n\nuse clear_coat::*;\nuse clear_coat::common_attrs_cbs::*;\n\nstruct CursorsCanvas {\n canvas: Canvas,\n}\n\nimpl CursorsCanvas {\n pub fn new() -> Self {\n CursorsCanvas {\n canvas: Canvas::new(),\n }\n }\n}\n\nunsafe impl Control for CursorsCanvas {\n fn handle(&self) -> *mut Ihandle {\n self.canvas.handle()\n }\n}\n\nfn create_cursors_page() -> Box<Control> {\n let page = vbox!(\n &CursorsCanvas::new()\n );\n Box::new(page)\n}\n\nfn main() {\n\n let dialog = Dialog::new();\n\n let tabs = Tabs::new();\n\n tabs.append_tabs(&[\n TabInfo::new(&*create_cursors_page()).title(\"Cursors\"),\n TabInfo::new(&Fill::new()).title(\"File Dialog\"),\n ]);\n\n dialog.append(&tabs).expect(\"failed to build the window\");\n dialog.set_title(\"Showcase\");\n\n dialog.show_xy(ScreenPosition::Center, ScreenPosition::Center)\n .expect(\"failed to show the window\");\n main_loop();\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Bring in Phauxfiles argument handler without specifics\n" }, { "from": "gpt", "value": "use getopts::Options;\nuse std::env::Args;\n\npub struct Arguments {\n pub program_name: String,\n pub exit: bool,\n}\n\nfn print_usage(program: &str, opts: Options) {\n let brief = format!(\"Usage: {} [options]\", program);\n print!(\"{}\", opts.usage(&*brief));\n}\n\npub fn parse_args(arguments: Args) -> Arguments {\n let mut opts = Options::new();\n opts.optflag(\"h\", \"help\", \"print this help menu\");\n\n let matches = match opts.parse(arguments) {\n Ok(m) => { m }\n Err(f) => { panic!(f.to_string()) }\n };\n\n let mut args = Arguments {\n program_name: \"\".to_string(),\n exit: matches.opt_present(\"h\"),\n };\n\n if args.exit {\n print_usage(&*args.program_name, opts);\n }\n\n args.entries = match matches.opt_str(\"n\") {\n Some(s) => match (&*s).parse() {\n Ok(x) => Some(x),\n Err(_) => None,\n },\n None => None,\n };\n\n args.filename = matches.opt_str(\"o\");\n\n args.port = match matches.opt_str(\"s\") {\n Some(s) => match (&*s).parse() {\n Ok(x) => Some(x),\n Err(_) => None,\n },\n None => None,\n };\n\n args\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Use pentium4 for base CPU on i686-pc-windows-msvc\n\nThis is in line with other targets.\r\n\r\nCloses #27646" }, { "from": "human", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse target::Target;\n\npub fn target() -> Target {\n let mut base = super::windows_msvc_base::opts();\n base.cpu = \"i686\".to_string();\n\n Target {\n llvm_target: \"i686-pc-windows-msvc\".to_string(),\n target_endian: \"little\".to_string(),\n target_pointer_width: \"32\".to_string(),\n arch: \"x86\".to_string(),\n target_os: \"windows\".to_string(),\n target_env: \"msvc\".to_string(),\n options: base,\n }\n}\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse target::Target;\n\npub fn target() -> Target {\n let mut base = super::windows_msvc_base::opts();\n base.cpu = \"pentium4\".to_string();\n\n Target {\n llvm_target: \"i686-pc-windows-msvc\".to_string(),\n target_endian: \"little\".to_string(),\n target_pointer_width: \"32\".to_string(),\n arch: \"x86\".to_string(),\n target_os: \"windows\".to_string(),\n target_env: \"msvc\".to_string(),\n options: base,\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add Rust code for proverb case\n\nIt passed all test cases\n" }, { "from": "gpt", "value": "pub fn build_proverb(text: Vec<&str>) -> String {\n let mut result = String::new();\n let mut iter = text.iter().peekable();\n\n let last = if text.len() < 3 { \"\" } else { \"horseshoe \" };\n\n while let Some(c) = iter.next() {\n if let Some(n) = iter.peek() {\n result += &format!(\"For want of a {} the {} was lost.\\n\", c, n);\n } else {\n result += &format!(\"And all for the want of a {}nail.\", last);\n }\n }\n\n result\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add dummy compilation test in replacement for examples\n" }, { "from": "gpt", "value": "//! This file contains a single test that is\n//! compiled but not run, just to ensure that\n//! the GL symbols are defined\n\nextern crate gl;\nextern crate libc;\n\n#[test]\n#[ignore]\nfn test() {\n\tgl::Clear(gl::COLOR_BUFFER_BIT);\n\tlet _: libc::c_uint = gl::CreateProgram();\n\tgl::CompileShader(5);\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test for async closures\n" }, { "from": "gpt", "value": "// rustfmt-edition: Edition2018\n\nfn main() {\n let async_closure = async {\n let x = 3;\n x\n };\n\n let f = async /* comment */ {\n let x = 3;\n x\n };\n\n let g = async /* comment */ move {\n let x = 3;\n x\n };\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Implement \"Roots of a function\" problem.\n" }, { "from": "gpt", "value": "// http://rosettacode.org/wiki/Roots_of_a_function\n\nfn find_roots<T: Copy + PartialOrd + Signed>(f: |T| -> T, start: T, stop: T,\n step: T, epsilon: T) -> Vec<T> {\n let mut ret = vec![];\n let mut current = start;\n while current < stop {\n if f(current).abs() < epsilon {\n ret.push(current);\n }\n current = current + step;\n }\n ret\n}\n\n#[test]\nfn test_find_roots() {\n let roots = find_roots(|x: f64| x*x*x - 3.0*x*x + 2.0*x,\n -1.0, 3.0, 0.0001, 0.00000001);\n let expected = [0.0f64, 1.0, 2.0];\n\n for (&a, &b) in roots.iter().zip(expected.iter()) {\n assert!((a - b).abs() < 0.0001);\n }\n}\n\n#[cfg(not(test))]\nfn main() {\n let roots = find_roots(|x: f64| x*x*x - 3.0*x*x + 2.0*x,\n -1.0, 3.0, 0.0001, 0.00000001);\n\n println!(\"roots of f(x) = x^3 - 3x^2 + 2x are: {}\", roots);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add example that utilizes terminal default colors\n" }, { "from": "gpt", "value": "extern crate cursive;\n\n\nuse cursive::Cursive;\nuse cursive::theme::{Color, Theme};\nuse cursive::views::TextView;\n\n\nfn custom_theme_from_cursive(siv: &Cursive) -> Theme {\n let mut theme = siv.current_theme().clone();\n theme.colors.background = Color::Default;\n theme\n}\n\nfn main() {\n let mut siv = Cursive::new();\n let theme = custom_theme_from_cursive(&siv);\n\n // We can quit by pressing `q`\n siv.add_global_callback('q', Cursive::quit);\n siv.set_theme(theme);\n\n siv.add_layer(TextView::new(\"Hello World with default terminal background color!\\n\\\n Press q to quit the application.\"));\n\n siv.run();\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for two sequence repetitions in a row\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// Check that we cannot have two sequence repetitions in a row.\n\nmacro_rules! foo {\n ( $($a:expr)* $($b:tt)* ) => { }; //~ ERROR sequence repetition followed by another sequence\n ( $($a:tt)* $($b:tt)* ) => { }; //~ ERROR sequence repetition followed by another sequence\n}\n\nfn main() { }\n" } ]
rust
chosen
[ { "from": "human", "value": "Add the commandline options example from the README to examples\n" }, { "from": "gpt", "value": "extern crate getopts;\nextern crate knob;\n\nuse getopts::optopt;\nuse knob::Settings;\n\nfn main() {\n let mut settings = Settings::new();\n settings.opt(optopt(\"p\", \"port\", \"the port to bind to\", \"4000\"));\n settings.opt(optopt(\"e\", \"environment\", \"the environment to run in\", \"\"));\n let errors = settings.load_os_args();\n if errors.is_some() {\n println!(\"{}\", settings.usage(\"Try one of these:\"));\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test for unsized tuple impls.\n" }, { "from": "gpt", "value": "// Copyright 2017 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(unsized_tuple_coercion)]\n\nuse std::collections::HashSet;\n\nfn main() {\n let x : &(i32, i32, [i32]) = &(0, 1, [2, 3]);\n let y : &(i32, i32, [i32]) = &(0, 1, [2, 3, 4]);\n let mut a = [y, x];\n a.sort();\n assert_eq!(a, [x, y]);\n\n assert_eq!(&format!(\"{:?}\", a), \"[(0, 1, [2, 3]), (0, 1, [2, 3, 4])]\");\n\n let mut h = HashSet::new();\n h.insert(x);\n h.insert(y);\n assert!(h.contains(x));\n assert!(h.contains(y));\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Implement a trait that get an HTTP response given an URL and headers\n" }, { "from": "gpt", "value": "use hyper::client::Client;\nuse hyper::client::response::Response;\nuse hyper::error::Error;\nuse hyper::header::Headers;\nuse hyper::method::Method;\n\n/// Trait that represents some methods to send a specific request\npub trait GetResponse {\n /// Given a specific URL, get the response from the target server\n fn get_http_response(url: &str) -> Result<Response, Error>;\n /// Given a specific URL and an header, get the response from the target server\n fn get_http_response_using_headers(url: &str, header: Headers) -> Result<Response, Error>;\n}\n\nimpl GetResponse for Client {\n fn get_http_response(url: &str) -> Result<Response, Error> {\n Client::new().request(Method::Get, url).send()\n }\n fn get_http_response_using_headers(url: &str,\n custom_header: Headers)\n -> Result<Response, Error> {\n Client::new().request(Method::Get, url).headers(custom_header).send()\n }\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add a prototype of the digest FFI API.\n" }, { "from": "gpt", "value": "extern crate ring;\n\nmacro_rules! wrap_algorithm {\n ( $wrapper_name:ident, $t:ty, $alg:expr ) => {\n /// Do NOT free the resulting pointer.\n #[no_mangle]\n pub unsafe fn $wrapper_name() -> *const $t {\n $alg as *const $t\n }\n }\n}\n\nwrap_algorithm!(ring_digest_algorithm_sha1, ring::digest::Algorithm,\n &ring::digest::SHA1);\nwrap_algorithm!(ring_digest_algorithm_sha256, ring::digest::Algorithm,\n &ring::digest::SHA256);\nwrap_algorithm!(ring_digest_algorithm_sha384, ring::digest::Algorithm,\n &ring::digest::SHA384);\nwrap_algorithm!(ring_digest_algorithm_sha512, ring::digest::Algorithm,\n &ring::digest::SHA512);\n\n/// Returns a pointer to a heap-allocated `ring::digest::Context`. You must\n/// call `ring_digest_context_finish` to free the returned context. \n#[no_mangle]\npub unsafe fn ring_digest_context_new(algorithm: *const ring::digest::Algorithm)\n -> *mut ring::digest::Context {\n if algorithm.is_null() {\n return std::ptr::null_mut();\n }\n Box::into_raw(Box::new(ring::digest::Context::new(&*algorithm)))\n}\n\n/// Calls `ctx.update()` with the given data.\n#[no_mangle]\npub unsafe fn ring_digest_context_update(ctx: *mut ring::digest::Context,\n p: *const u8, len: usize) {\n (*ctx).update(std::slice::from_raw_parts(p, len))\n}\n\n/// Frees a context created by `ring_digest_context_new`.\n#[no_mangle]\npub unsafe fn ring_digest_context_finish(ctx: *mut ring::digest::Context,\n out: *mut u8, out_capacity: usize)\n -> usize {\n // We can't call `finish` on (*ctx). `x.finish()` consumes `x` but in the\n // FFI interface we can't rely on the caller honoring Rust's move semantics.\n let copy = (*ctx).clone();\n let digest = copy.finish();\n let digest = digest.as_ref();\n let len = digest.len();\n if len > out_capacity {\n return 0;\n }\n std::ptr::copy_nonoverlapping(digest.as_ptr(), out, len);\n len\n}\n\n#[no_mangle]\npub unsafe fn ring_digest_context_delete(ctx: *mut ring::digest::Context) {\n let _ = Box::from_raw(ctx);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Replace is_none() -> unwrap() with unwrap_or_else()\n" }, { "from": "human", "value": "use std::process::exit;\n\nuse libimagdiary::diary::Diary;\nuse libimagentryview::viewer::Viewer;\nuse libimagentryview::builtin::plain::PlainViewer;\nuse libimagrt::runtime::Runtime;\nuse libimagerror::trace::trace_error;\n\nuse util::get_diary_name;\n\npub fn view(rt: &Runtime) {\n let diaryname = get_diary_name(rt);\n if diaryname.is_none() {\n warn!(\"No diary name\");\n exit(1);\n }\n let diaryname = diaryname.unwrap();\n let diary = Diary::open(rt.store(), &diaryname[..]);\n let show_header = rt.cli().subcommand_matches(\"view\").unwrap().is_present(\"show-header\");\n\n match diary.entries() {\n Ok(entries) => {\n let pv = PlainViewer::new(show_header);\n for entry in entries.into_iter().filter_map(Result::ok) {\n let id = entry.diary_id();\n println!(\"{} :\\n\", id);\n if let Err(e) = pv.view_entry(&entry) {\n trace_error(&e);\n };\n println!(\"\\n---\\n\");\n }\n },\n Err(e) => trace_error(&e),\n }\n}\n\n" }, { "from": "gpt", "value": "use std::process::exit;\n\nuse libimagdiary::diary::Diary;\nuse libimagentryview::viewer::Viewer;\nuse libimagentryview::builtin::plain::PlainViewer;\nuse libimagrt::runtime::Runtime;\nuse libimagerror::trace::trace_error;\n\nuse util::get_diary_name;\n\npub fn view(rt: &Runtime) {\n let diaryname = get_diary_name(rt).unwrap_or_else(|| {\n warn!(\"No diary name\");\n exit(1);\n });\n\n let diary = Diary::open(rt.store(), &diaryname[..]);\n let show_header = rt.cli().subcommand_matches(\"view\").unwrap().is_present(\"show-header\");\n\n match diary.entries() {\n Ok(entries) => {\n let pv = PlainViewer::new(show_header);\n for entry in entries.into_iter().filter_map(Result::ok) {\n let id = entry.diary_id();\n println!(\"{} :\\n\", id);\n if let Err(e) = pv.view_entry(&entry) {\n trace_error(&e);\n };\n println!(\"\\n---\\n\");\n }\n },\n Err(e) => trace_error(&e),\n }\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add 3rd example, simple linked list and move\n" }, { "from": "gpt", "value": "enum SimpleList<T> {\n Cons(T, Box<SimpleList<T>>),\n Nil,\n}\n\nfn length<T>(xs: &SimpleList<T>) -> int {\n match xs {\n &Cons(_, ref ys) => 1 + length(*ys),\n &Nil => 0,\n }\n}\n\nfn main() {\n let mut xs = box Nil;\n xs = box Cons(3, xs);\n xs = box Cons(2, xs);\n xs = box Cons(1, xs);\n let ys = xs;\n println!(\"{}\", length(ys)); // OK\n // xs is moved. It will be compiler error.\n // println!(\"{}\", length(xs)); // NG!\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add example for merge requests\n" }, { "from": "gpt", "value": "\nextern crate gitlab_api as gitlab;\n\nuse std::env;\n#[macro_use]\nextern crate log;\nextern crate env_logger;\n\nuse gitlab::GitLab;\nuse gitlab::merge_requests;\n\n\nfn main() {\n env_logger::init().unwrap();\n info!(\"starting up\");\n\n let hostname = match env::var(\"GITLAB_HOSTNAME\") {\n Ok(val) => val,\n Err(_) => {\n let default = String::from(\"gitlab.com\");\n println!(\"Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.\",\n default);\n default\n }\n };\n\n let token = match env::var(\"GITLAB_TOKEN\") {\n Ok(val) => val,\n Err(_) => {\n panic!(\"Please set environment variable 'GITLAB_TOKEN'. Take it from \\\n http://{}/profile/account\",\n hostname);\n }\n };\n\n let gl = GitLab::new_https(&hostname, &token);\n\n let merge_request = gl.merge_request(merge_requests::single::Listing::new(142, 418)).unwrap();\n println!(\"merge_request: {:?}\", merge_request);\n\n let merge_requests = gl.merge_requests(merge_requests::Listing::new(142)).unwrap();\n println!(\"merge_requests: {:?}\", merge_requests);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add tests for null pointer opt.\n" }, { "from": "gpt", "value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n\nuse std::gc::Gc;\nuse std::mem::size_of;\n\ntrait Trait {}\n\nfn main() {\n // Closures - || / proc()\n assert_eq!(size_of::<proc()>(), size_of::<Option<proc()>>());\n assert_eq!(size_of::<||>(), size_of::<Option<||>>());\n\n // Functions\n assert_eq!(size_of::<fn(int)>(), size_of::<Option<fn(int)>>());\n assert_eq!(size_of::<extern \"C\" fn(int)>(), size_of::<Option<extern \"C\" fn(int)>>());\n\n // Slices - &str / &[T] / &mut [T]\n assert_eq!(size_of::<&str>(), size_of::<Option<&str>>());\n assert_eq!(size_of::<&[int]>(), size_of::<Option<&[int]>>());\n assert_eq!(size_of::<&mut [int]>(), size_of::<Option<&mut [int]>>());\n\n // Traits - Box<Trait> / &Trait / &mut Trait\n assert_eq!(size_of::<Box<Trait>>(), size_of::<Option<Box<Trait>>>());\n assert_eq!(size_of::<&Trait>(), size_of::<Option<&Trait>>());\n assert_eq!(size_of::<&mut Trait>(), size_of::<Option<&mut Trait>>());\n\n // Pointers - Box<T> / Gc<T>\n assert_eq!(size_of::<Box<int>>(), size_of::<Option<Box<int>>>());\n assert_eq!(size_of::<Gc<int>>(), size_of::<Option<Gc<int>>>());\n\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add example from lkuper's intern talk to the test suite.\n" }, { "from": "gpt", "value": "// Example from lkuper's intern talk, August 2012.\n\ntrait Equal {\n fn isEq(a: self) -> bool;\n}\n\nenum Color { cyan, magenta, yellow, black }\n\nimpl Color : Equal {\n fn isEq(a: Color) -> bool {\n match (self, a) {\n (cyan, cyan) => { true }\n (magenta, magenta) => { true }\n (yellow, yellow) => { true }\n (black, black) => { true }\n _ => { false }\n }\n }\n}\n\nenum ColorTree {\n leaf(Color),\n branch(@ColorTree, @ColorTree)\n}\n\nimpl ColorTree : Equal {\n fn isEq(a: ColorTree) -> bool {\n match (self, a) {\n (leaf(x), leaf(y)) => { x.isEq(y) }\n (branch(l1, r1), branch(l2, r2)) => { \n (*l1).isEq(*l2) && (*r1).isEq(*r2)\n }\n _ => { false }\n }\n }\n}\n\nfn main() {\n assert cyan.isEq(cyan);\n assert magenta.isEq(magenta);\n assert !cyan.isEq(yellow);\n assert !magenta.isEq(cyan);\n\n assert leaf(cyan).isEq(leaf(cyan));\n assert !leaf(cyan).isEq(leaf(yellow));\n\n assert branch(@leaf(magenta), @leaf(cyan))\n .isEq(branch(@leaf(magenta), @leaf(cyan)));\n\n assert !branch(@leaf(magenta), @leaf(cyan))\n .isEq(branch(@leaf(magenta), @leaf(magenta)));\n\n log(error, \"Assertions all succeeded!\");\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add a test to prevent regression\n\nThe way it defines implementations is unrealistic though.\n" }, { "from": "gpt", "value": "// Copyright 2018 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\npub trait MyIterator {\n}\n\npub struct MyStruct<T>(T);\n\nmacro_rules! array_impls {\n ($($N:expr)+) => {\n $(\n impl<'a, T> MyIterator for &'a MyStruct<[T; $N]> {\n }\n )+\n }\n}\n\n// @has issue_53812/trait.MyIterator.html '//*[@id=\"implementors-list\"]//h3[1]' 'MyStruct<[T; 0]>'\narray_impls! { 10 3 2 1 0 }\n" } ]
rust
chosen
[ { "from": "human", "value": "Add RMS example to the examples directory\n\nA similar example was already in the readme and the docs, but it is\nuseful to have a runnable program to test whether Hound can read a given\nfile.\n" }, { "from": "gpt", "value": "// Hound -- A wav encoding and decoding library in Rust\n// Copyright (C) 2017 Ruud van Asseldonk\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// A copy of the License has been included in the root of the repository.\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// This example computes the root mean square (rms) of an audio file with\n// integer or float samples, of at most 32 bits per sample. It is a slightly\n// more elaborate version of the example found in the readme, mostly useful for\n// checking whether Hound can read a specific file.\n\nextern crate hound;\n\nuse std::env;\nuse std::io;\n\n/// Compute the RMS of either integers or float samples.\nfn compute_rms<S, R>(reader: &mut hound::WavReader<R>) -> f64\nwhere\n f64: From<S>,\n S: hound::Sample,\n R: io::Read,\n{\n let sqr_sum = reader.samples::<S>().fold(0.0, |sqr_sum, s| {\n let sample = f64::from(s.unwrap());\n sqr_sum + sample * sample\n });\n (sqr_sum / reader.len() as f64).sqrt()\n}\n\nfn main() {\n // Compute the RMS for all files given on the command line.\n for fname in env::args().skip(1) {\n let mut reader = hound::WavReader::open(&fname).unwrap();\n let rms = match reader.spec().sample_format {\n hound::SampleFormat::Float => compute_rms::<f32, _>(&mut reader),\n hound::SampleFormat::Int => compute_rms::<i32, _>(&mut reader),\n };\n println!(\"{}: {:0.1}\", fname, rms);\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add an XFAILed test for native \"llvm\" modules\n\nThis functionality is completely broken\n" }, { "from": "gpt", "value": "// xfail-test\n\nnative \"llvm\" mod llvm {\n fn thesqrt(n: float) -> float = \"sqrt.f64\";\n}\n\nfn main() {\n let s = llvm::thesqrt(4.0);\n assert 1.9 < s && s < 2.1;\n}" } ]
rust
chosen
[ { "from": "human", "value": "Add a FIXME note about what's missing\n" }, { "from": "gpt", "value": "// ignore-test\n\n#![allow(incomplete_features)]\n#![feature(const_mut_refs)]\n#![feature(inline_const)]\n\nuse std::marker::PhantomData;\n\n#[derive(PartialEq, Eq)]\npub struct InvariantRef<'a, T: ?Sized>(&'a T, PhantomData<&'a mut &'a T>);\n\nimpl<'a, T: ?Sized> InvariantRef<'a, T> {\n pub const fn new(r: &'a T) -> Self {\n InvariantRef(r, PhantomData)\n }\n}\n\nimpl<'a> InvariantRef<'a, ()> {\n pub const NEW: Self = InvariantRef::new(&());\n}\n\nfn match_invariant_ref<'a>() {\n let y = ();\n match InvariantRef::new(&y) {\n //~^ ERROR `y` does not live long enough [E0597]\n // FIXME(nbdd0121): This should give the same error as `InvariantRef::<'a>::NEW` (without\n // const block)\n const { InvariantRef::<'a>::NEW } => (),\n }\n}\n\nfn main() {\n match_invariant_ref();\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Test against accesses to uninitialized fields.\n" }, { "from": "gpt", "value": "// Copyright 2017 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// revisions: ast mir\n//[mir]compile-flags: -Z emit-end-regions -Z borrowck-mir\n\n// Check that do not allow access to fields of uninitialized or moved\n// structs.\n\n#[derive(Default)]\nstruct Point {\n x: isize,\n y: isize,\n}\n\n#[derive(Default)]\nstruct Line {\n origin: Point,\n middle: Point,\n target: Point,\n}\n\nimpl Line { fn consume(self) { } }\n\nfn main() {\n let mut a: Point;\n let _ = a.x + 1; //[ast]~ ERROR use of possibly uninitialized variable: `a.x`\n //[mir]~^ ERROR [E0381]\n //[mir]~| ERROR (Mir) [E0381]\n\n let mut line1 = Line::default();\n let _moved = line1.origin;\n let _ = line1.origin.x + 1; //[ast]~ ERROR use of collaterally moved value: `line1.origin.x`\n //[mir]~^ [E0382]\n //[mir]~| (Mir) [E0381]\n\n let mut line2 = Line::default();\n let _moved = (line2.origin, line2.middle);\n line2.consume(); //[ast]~ ERROR use of partially moved value: `line2` [E0382]\n //[mir]~^ [E0382]\n //[mir]~| (Mir) [E0381]\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add an unit test for add_global_mapping.\n" }, { "from": "gpt", "value": "extern crate libc;\nextern crate llvm;\n\nuse libc::c_void;\nuse llvm::*;\nuse std::mem;\n\npub extern \"C\" fn test_func3(x: f64) -> f64 {\n x\n}\n\n#[test]\nfn add_global_mapping() {\n let ctx = Context::new();\n let module = Module::new(\"test_func_find\", &ctx); \n module.verify().expect(\"verifying the module failed...\");\n \n let ee = JitEngine::new(&module, JitOptions {opt_level: 0}).unwrap();\n \n let ret_ty = Type::get::<f64>(&ctx);\n let param_tys = vec![Type::get::<f64>(&ctx)];\n let fn_ty = Type::function_ty(ret_ty, &param_tys);\n let function = module.add_function(\"test_func3\", fn_ty);\n let fn_ptr: *const c_void = unsafe { mem::transmute(test_func3) };\n unsafe { ee.add_global_mapping(function, fn_ptr); } \n \n\tlet f: fn(f64) -> f64;\n f = match unsafe { ee.get_function_raw(function) } {\n \tSome(f) => unsafe { mem::transmute(f)},\n \t_ => panic!(\"get_function_raw: couldn't find test_func3\")\n };\n \n assert_eq!(98.0f64, f(98.0f64));\n}" } ]
rust
chosen
[ { "from": "system", "value": "Add a fat byte-slice coercion test.\n" }, { "from": "human", "value": "#![feature(custom_attribute)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn empty() -> &'static str {\n \"\"\n}\n\n#[miri_run]\nfn hello() -> &'static str {\n \"Hello, world!\"\n}\n\n#[miri_run]\nfn hello_bytes() -> &'static [u8; 13] {\n b\"Hello, world!\"\n}\n" }, { "from": "gpt", "value": "#![feature(custom_attribute)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn empty() -> &'static str {\n \"\"\n}\n\n#[miri_run]\nfn hello() -> &'static str {\n \"Hello, world!\"\n}\n\n#[miri_run]\nfn hello_bytes() -> &'static [u8; 13] {\n b\"Hello, world!\"\n}\n\n#[miri_run]\nfn hello_bytes_fat() -> &'static [u8] {\n b\"Hello, world!\"\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for comparing md5 checksums\n" }, { "from": "gpt", "value": "extern crate flac;\nextern crate crypto;\n\nuse crypto::digest::Digest;\nuse crypto::md5::Md5;\nuse flac::Stream;\nuse std::cmp;\n\nfn to_bytes(value: i32, buffer: &mut [u8]) {\n buffer[0] = value as u8;\n buffer[1] = (value >> 8) as u8;\n buffer[2] = (value >> 16) as u8;\n buffer[3] = (value >> 24) as u8;\n}\n\nfn get_offset(sample_size: usize) -> usize {\n let bits_per_sample = cmp::max(sample_size, 8);\n\n bits_per_sample / 8\n}\n\n#[test]\nfn test_decoded_md5_sum() {\n let filename = \"tests/assets/input-pictures.flac\";\n\n let mut stream = Stream::from_file(filename).unwrap();\n let mut buffer = [0; 4];\n let mut md5 = Md5::new();\n let mut md5_sum = [0; 16];\n\n let info = stream.info();\n let offset = get_offset(info.bits_per_sample as usize);\n\n for sample in stream.iter() {\n to_bytes(sample, &mut buffer);\n\n md5.input(&buffer[0..offset]);\n }\n\n md5.result(&mut md5_sum);\n\n assert_eq!(md5_sum, info.md5_sum);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "test: Fix problem with check-fast. rs=burningtree\n" }, { "from": "human", "value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse std::cast;\nuse std::ptr;\nuse std::sys;\n\nfn addr_of<T>(ptr: &T) -> uint {\n let ptr = ptr::to_unsafe_ptr(ptr);\n unsafe { ptr as uint }\n}\n\nfn is_aligned<T>(ptr: &T) -> bool {\n unsafe {\n let addr: uint = ::cast::transmute(ptr);\n (addr % sys::min_align_of::<T>()) == 0\n }\n}\n\npub fn main() {\n let x = Some(0u64);\n match x {\n None => fail!(),\n Some(ref y) => assert!(is_aligned(y))\n }\n}\n" }, { "from": "gpt", "value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse std::cast;\nuse std::ptr;\nuse std::sys;\n\nfn addr_of<T>(ptr: &T) -> uint {\n let ptr = ptr::to_unsafe_ptr(ptr);\n unsafe { ptr as uint }\n}\n\nfn is_aligned<T>(ptr: &T) -> bool {\n unsafe {\n let addr: uint = cast::transmute(ptr);\n (addr % sys::min_align_of::<T>()) == 0\n }\n}\n\npub fn main() {\n let x = Some(0u64);\n match x {\n None => fail!(),\n Some(ref y) => assert!(is_aligned(y))\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for macro disambiguators\n" }, { "from": "gpt", "value": "#![crate_name = \"foo\"]\n#![deny(rustdoc::broken_intra_doc_links)]\n\n//! [foo!()]\n// @has foo/index.html '//a[@href=\"macro.foo.html\"]' 'foo!()'\n\n//! [foo!{}]\n// @has - '//a[@href=\"macro.foo.html\"]' 'foo!{}'\n\n//! [foo![]](foo![])\n// @has - '//a[@href=\"macro.foo.html\"]' 'foo![]'\n\n//! [foo1](foo!())\n// @has - '//a[@href=\"macro.foo.html\"]' 'foo1'\n\n//! [foo2](foo!{})\n// @has - '//a[@href=\"macro.foo.html\"]' 'foo2'\n\n//! [foo3](foo![])\n// @has - '//a[@href=\"macro.foo.html\"]' 'foo3'\n\n#[macro_export]\nmacro_rules! foo {\n () => {};\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add integration test for macro\n" }, { "from": "gpt", "value": "//! Having these as an integration test checks that the visibility of the macros\n//! and their dependencies is valid for use by external libraries.\n\n#[macro_use]\n// Rename the import to check that the macros don't use the literal crate name\nextern crate hamlet as willy;\n\n// I would really like to do:\n//\n// ```\n// #![no_std]\n// #![no_implicit_prelude]\n// #[macro_use]\n// extern crate std as bob;\n// ```\n//\n// but macros are too unhygienic :(\n\n// We don't `use` anything here to check the macros only use fully qualified\n// paths.\n\n#[test]\nfn empty_attr_set() {\n assert_eq!(attr_set!().0.into_owned(), vec![]);\n}\n\n#[test]\nfn single_attr() {\n assert_eq!(\n attr_set!(id = \"foo\").0.into_owned(),\n vec![\n willy::Attribute::new(\"id\", \"foo\"),\n ]);\n}\n\n#[test]\nfn multi_attr() {\n assert_eq!(\n attr_set!(id = \"foo\", class = \"bar\").0.into_owned(),\n vec![\n willy::Attribute::new(\"id\", \"foo\"),\n willy::Attribute::new(\"class\", \"bar\"),\n ]);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test file for distinct ty_native types\n\nThis should have gone into patch\n77f5d14f14630da997f13de28ea86e8320957180, had I not forgotten to add\nthe file.\n" }, { "from": "gpt", "value": "// error-pattern:expected native but found native\nuse std;\n\nfn main() {\n let std::os::libc::FILE f = std::io::rustrt::rust_get_stdin();\n std::os::libc::opendir(f);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a test for exported symbols.\n" }, { "from": "gpt", "value": "// Copyright 2016 Mozilla\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use\n// this file except in compliance with the License. You may obtain a copy of the\n// License at http://www.apache.org/licenses/LICENSE-2.0\n// Unless required by applicable law or agreed to in writing, software distributed\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations under the License.\n\n// Verify that our public API can be imported.\n\nextern crate mentat;\n\n#[allow(unused_imports)]\nuse mentat::{\n Conn,\n QueryResults,\n TypedValue,\n ValueType,\n conn,\n new_connection,\n};\n" } ]
rust
chosen