conversations listlengths 2 3 | source stringclasses 1 value | stack stringclasses 1 value |
|---|---|---|
[
{
"from": "human",
"value": "Check const-propagation of borrows of unsized places\n"
},
{
"from": "gpt",
"value": "// run-pass (ensure that const-prop is run)\n\nstruct A<T: ?Sized>(T);\n\nfn main() {\n let _x = &(&A([2, 3]) as &A<[i32]>).0 as *const [i32] as *const i32;\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for silenced unused params in derive\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#![deny(warnings)]\n\n#[derive(Hash, Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Copy)]\nstruct Foo;\n\nfn main() {\n let _ = Foo;\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an inlining debuginfo test\n"
},
{
"from": "gpt",
"value": "#![crate_type=\"rlib\"]\n// compile-flags: -Copt-level=3 -g\n\n#[no_mangle]\n#[inline(always)]\npub extern \"C\" fn callee(x: u32) -> u32 {\n x + 4\n}\n\n// CHECK-LABEL: caller\n// CHECK: call void @llvm.dbg.value(metadata i32 %y, metadata !{{.*}}, metadata !DIExpression(DW_OP_constu, 3, DW_OP_minus, DW_OP_stack_value)), !dbg [[A:!.*]]\n// CHECK: [[A]] = !DILocation(line: {{.*}}, scope: {{.*}}, inlinedAt: {{.*}})\n#[no_mangle]\npub extern \"C\" fn caller(y: u32) -> u32 {\n callee(y - 3)\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add example to load and print bundle\n\nAlso allows quick testing if local kbdgen bundles can be parsed, e.g.\nlike this:\n\n fd -0 .kbdgen ../giellalt/ | xargs -0 -I % cargo r --example load_bundle -- %\n"
},
{
"from": "gpt",
"value": "use kbdgen::{Load, ProjectBundle};\nuse snafu::ErrorCompat;\n\nfn main() {\n let path = std::env::args()\n .nth(1)\n .expect(\"Pass path to `.kbdgen` bundle as argument\");\n\n match ProjectBundle::load(&path) {\n Ok(bundle) => eprintln!(\"{:#?}\", bundle),\n Err(e) => {\n eprintln!(\"An error occurred: {}\", e);\n if let Some(backtrace) = ErrorCompat::backtrace(&e) {\n println!(\"{}\", backtrace);\n }\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add simple assembler parsing example\n\nHas proven useful for finding assembler statements that the parser fail\nto understand, by loading larger examples found online.\n"
},
{
"from": "gpt",
"value": "extern crate r68k_tools;\nextern crate pest;\n\nuse r68k_tools::assembler::parser::Rdp;\nuse std::io::{BufReader, BufRead};\nuse std::fs::File;\nuse pest::{Parser, StringInput};\nuse std::env;\n\nfn main() {\n let file = if let Some(asmfile) = env::args().nth(1) {\n File::open(asmfile.as_str()).expect(\"could not open file\")\n } else {\n panic!(\"Provide the path to an assembler file as first argument, to have it parsed\");\n };\n let reader = BufReader::new(&file);\n let mut correct = 0;\n let mut fail = 0;\n let mut unended = 0;\n let mut lines = 0;\n for (num, line) in reader.lines().enumerate() {\n let input = match line {\n Ok(text) => text,\n Err(ex) => {\n println!(\"errd:{:04}: {}\", num+1, ex);\n continue;\n }\n };\n let mut parser = Rdp::new(StringInput::new(&input));\n if parser.statement() {\n if parser.end() {\n correct += 1;\n } else {\n unended += 1;\n let qc = parser.queue_with_captures();\n println!(\"!end:{:04}: {:80} : {:?} (expected {:?})\", num+1, input, qc, parser.expected());\n };\n } else {\n fail += 1;\n println!(\"fail:{:04}: {}\", num+1, input);\n };\n lines = num;\n }\n println!(\"= END = total lines {:04}: correct {}, failed {}, incomplete {}\", lines+1, correct, fail, unended);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add benchmarks for zeros / default\n"
},
{
"from": "gpt",
"value": "#![feature(test)]\n\nextern crate test;\nuse test::Bencher;\n\n#[macro_use(s)]\nextern crate ndarray;\nuse ndarray::prelude::*;\n\n#[bench]\nfn default_f64(bench: &mut Bencher) {\n bench.iter(|| {\n Array::<f64, _>::default((128, 128))\n })\n}\n\n#[bench]\nfn zeros_f64(bench: &mut Bencher) {\n bench.iter(|| {\n Array::<f64, _>::zeros((128, 128))\n })\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for closure drop.\n"
},
{
"from": "gpt",
"value": "struct Foo<'a>(&'a mut bool);\n\nimpl<'a> Drop for Foo<'a> {\n fn drop(&mut self) {\n *self.0 = true;\n }\n}\n\nfn f<T: FnOnce()>(t: T) {\n t()\n}\n\nfn main() {\n let mut ran_drop = false;\n {\n // FIXME: v is a temporary hack to force the below closure to be a FnOnce-only closure\n // (with sig fn(self)). Without it, the closure sig would be fn(&self) which requires a\n // shim to call via FnOnce::call_once, and Miri's current shim doesn't correctly call\n // destructors.\n let v = vec![1];\n let x = Foo(&mut ran_drop);\n let g = move || {\n let _ = x;\n drop(v); // Force the closure to be FnOnce-only by using a capture by-value.\n };\n f(g);\n }\n assert!(ran_drop);\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add tests for `if let`\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\npub fn main() {\n let x = Some(3i);\n if let Some(y) = x {\n assert_eq!(y, 3i);\n } else {\n fail!(\"if-let failed\");\n }\n let mut worked = false;\n if let Some(_) = x {\n worked = true;\n }\n assert!(worked);\n let clause: uint;\n if let None = Some(\"test\") {\n clause = 1;\n } else if 4u > 5 {\n clause = 2;\n } else if let Ok(()) = Err::<(),&'static str>(\"test\") {\n clause = 3;\n } else {\n clause = 4;\n }\n assert_eq!(clause, 4u);\n\n if 3i > 4 {\n fail!(\"bad math\");\n } else if let 1 = 2i {\n fail!(\"bad pattern match\");\n }\n\n enum Foo {\n One,\n Two(uint),\n Three(String, int)\n }\n\n let foo = Three(\"three\".to_string(), 42i);\n if let One = foo {\n fail!(\"bad pattern match\");\n } else if let Two(_x) = foo {\n fail!(\"bad pattern match\");\n } else if let Three(s, _) = foo {\n assert_eq!(s.as_slice(), \"three\");\n } else {\n fail!(\"bad else\");\n }\n\n if false {\n fail!(\"wat\");\n } else if let a@Two(_) = Two(42u) {\n if let Two(b) = a {\n assert_eq!(b, 42u);\n } else {\n fail!(\"fail in nested if-let\");\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add solution to problem 48\n"
},
{
"from": "gpt",
"value": "#[macro_use] extern crate libeuler;\nextern crate num;\n\nuse num::bigint::{BigInt, ToBigInt};\nuse num::traits::{Zero, One, ToPrimitive, PrimInt};\n\n/// The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.\n///\n/// Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.\nfn main() {\n solutions! {\n sol naive {\n let tenten = 10.pow(10);\n let sum = (1..1001)\n .map(|i| powmod(i, i, tenten))\n .fold(0, |c, v| {\n c + v\n });\n\n sum % tenten\n }\n }\n}\n\n// Based on algorithm found here:\n// http://stackoverflow.com/questions/8287144/modulus-power-of-big-numbers\nfn powmod(b: i64, e: i64, m: i64) -> i64 {\n if b < 1 || e < 0 || m < 1 {\n return -1;\n }\n\n let mut base = b.to_bigint().unwrap();\n let mut exponent = e.to_bigint().unwrap();\n let modulus = m.to_bigint().unwrap();\n\n let two = BigInt::one() + BigInt::one();\n\n let mut result = BigInt::one();\n while exponent > BigInt::zero() {\n if (&exponent % &two) == BigInt::one() {\n result = (result * &base) % &modulus;\n }\n base = (&base * &base) % &modulus;\n exponent = &exponent / &two;\n }\n\n result.to_i64().unwrap()\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix the tests broken by replacing `task` with `thread`\n"
},
{
"from": "human",
"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// error-pattern:Ensure that the child thread runs by panicking\n\nuse std::thread;\n\nfn main() {\n // the purpose of this test is to make sure that thread::spawn()\n // works when provided with a bare function:\n let r = thread::spawn(startfn).join();\n if r.is_err() {\n panic!()\n }\n}\n\nfn startfn() {\n assert!(\"Ensure that the child task runs by panicking\".is_empty());\n}\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// error-pattern:Ensure that the child thread runs by panicking\n\nuse std::thread;\n\nfn main() {\n // the purpose of this test is to make sure that thread::spawn()\n // works when provided with a bare function:\n let r = thread::spawn(startfn).join();\n if r.is_err() {\n panic!()\n }\n}\n\nfn startfn() {\n assert!(\"Ensure that the child thread runs by panicking\".is_empty());\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Update error message and un-xfail test\n"
},
{
"from": "human",
"value": "// xfail-test\n// error-pattern:unresolved import: m::f\nuse x = m::f;\n\nmod m {\n #[legacy_exports];\n}\n\nfn main() {\n}\n"
},
{
"from": "gpt",
"value": "use x = m::f; //~ ERROR failed to resolve import\n\nmod m {\n #[legacy_exports];\n}\n\nfn main() {\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add missing example for testing the drop/ memory leakage\n"
},
{
"from": "gpt",
"value": "extern crate libmodbus_sys as raw;\nextern crate libmodbus_rs;\n\nuse libmodbus_rs::modbus::{Modbus};\n\n\nfn main() {\n // 1. Parameter Serial Interface `/dev/ttyUSB0`\n let device: String = std::env::args().nth(1).unwrap();\n // 2. Parameter SlaveID\n let slave_id: i32 = std::env::args().nth(2).unwrap().parse().unwrap();\n\n let mut modbus = Modbus::new_rtu(&device, 9600, 'N', 8, 1);\n let _ = modbus.set_slave(slave_id);\n let _ = modbus.set_debug(true);\n\n match modbus.connect() {\n Err(_) => { modbus.free(); }\n Ok(_) => {}\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Check if enum_map! can be used on variantless enum\n"
},
{
"from": "gpt",
"value": "#![no_std]\n\n#[macro_use]\nextern crate enum_map;\n\nuse enum_map::EnumMap;\n\n#[derive(EnumMap)]\nenum Void {}\n\n#[test]\nfn empty_map() {\n let void: EnumMap<Void, Void> = enum_map! {};\n assert!(void.is_empty());\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add equivalent test in src/test/rustdoc\n"
},
{
"from": "gpt",
"value": "// edition:2018\n\n#![no_core]\n#![feature(no_core)]\n\n// @count issue_89852/index.html '//*[@class=\"macro\"]' 2\n// @has - '//*[@class=\"macro\"]/@href' 'macro.repro.html'\n#[macro_export]\nmacro_rules! repro {\n () => {};\n}\n\n// @!has issue_89852/macro.repro.html '//*[@class=\"macro\"]/@content' 'repro2'\npub use crate::repro as repro2;\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add Depth-First Search using The Rust Programming Language\n"
},
{
"from": "gpt",
"value": "use std::io::stdin;\n\n// DFS receives a graph and the start point\nfn dfs(graph: &mut Vec<Vec<usize>>, start: usize) {\n let mut visited: Box<Vec<bool>> = Box::new(Vec::new());\n visited.resize(graph.len(), false);\n\n dfs_util(&graph, start, &mut visited);\n}\n\nfn dfs_util(graph: &[Vec<usize>], value: usize, visited: &mut Box<Vec<bool>>) {\n visited[value] = true;\n println!(\"{}\", value);\n\n for node in &graph[value] {\n if !visited[*node] {\n dfs_util(graph, *node, visited);\n }\n } \n}\n\nfn add_edge(graph: &mut Vec<Vec<usize>>, u: usize, v: usize) {\n graph[u].push(v);\n}\n\nfn main() {\n let mut edges: usize;\n let mut graph: Vec<Vec<usize>> = Vec::new();\n graph.resize(100, vec![]);\n\n // Read number of edges from user\n let mut input: String = String::new();\n stdin().read_line(&mut input).unwrap(); \n edges = input.trim().parse::<u32>().unwrap() as usize;\n\n while edges > 0 {\n let u: usize;\n let v: usize;\n\n // Read u and v by splitting input into words and reading the first words found\n let mut input: String = String::new();\n stdin().read_line(&mut input).unwrap();\n let mut words = input.split_whitespace();\n u = words.next().unwrap().parse::<u32>().unwrap() as usize;\n v = words.next().unwrap().parse::<u32>().unwrap() as usize;\n\n add_edge(&mut graph, u, v);\n\n edges = edges - 1;\n }\n\n let start: usize;\n let mut input: String = String::new();\n stdin().read_line(&mut input).unwrap();\n start = input.trim().parse::<u32>().unwrap() as usize;\n\n dfs(&mut graph, start);\n}\n\n#[test]\nfn test_dfs_with_graph() {\n let mut graph: Vec<Vec<usize>> = Vec::new();\n graph.resize(4, vec![]);\n\n add_edge(&mut graph, 0, 1);\n add_edge(&mut graph, 0, 2);\n add_edge(&mut graph, 1, 2);\n add_edge(&mut graph, 2, 0);\n add_edge(&mut graph, 2, 3);\n add_edge(&mut graph, 3, 3);\n\n println!(\"DFS Starting from vertex 2\");\n\n dfs(&mut graph, 2);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Update old xfailing spawn/bind/join test\n"
},
{
"from": "human",
"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//xfail-test\n\nextern mod std;\n\nfn f(x : @{a:int, b:int}) {\n assert!((x.a == 10));\n assert!((x.b == 12));\n}\n\npub fn main() {\n let z : @{a:int, b:int} = @{ a : 10, b : 12};\n let p = task::_spawn(bind f(z));\n task::join_id(p);\n}\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\nextern mod std;\nuse core::task::spawn;\n\nstruct Pair {\n a: int,\n b: int\n}\n\npub fn main() {\n let z = ~Pair { a : 10, b : 12};\n \n let f: ~fn() = || {\n assert!((z.a == 10));\n assert!((z.b == 12));\n };\n\n spawn(f);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Allow '$' in rust files\n"
},
{
"from": "human",
"value": "pub fn editor(source: &str) -> String {\n format!(\"<div id=\\\"active-code\\\">\n<button class=\\\"btn btn-primary\\\" type=\\\"button\\\" id=\\\"run-code\\\">Run</button>\n<button class=\\\"btn btn-primary\\\" type=\\\"button\\\" id=\\\"reset-code\\\">Reset</button>\n<div id=\\\"editor\\\">{}</div>\n<div id=\\\"result\\\"></div>\n</div>\", escape(source))\n}\n\nfn escape(source: &str) -> String {\n let mut s = String::new();\n\n for chr in source.trim().chars() {\n match chr {\n '*' => s.push_str(\"*\"),\n '<' => s.push_str(\"<\"),\n '>' => s.push_str(\">\"),\n '\\\\' => s.push_str(\"\\"),\n '_' => s.push_str(\"_\"),\n '`' => s.push_str(\"`\"),\n chr => s.push(chr),\n }\n }\n\n s\n}\n"
},
{
"from": "gpt",
"value": "pub fn editor(source: &str) -> String {\n format!(\"<div id=\\\"active-code\\\">\n<button class=\\\"btn btn-primary\\\" type=\\\"button\\\" id=\\\"run-code\\\">Run</button>\n<button class=\\\"btn btn-primary\\\" type=\\\"button\\\" id=\\\"reset-code\\\">Reset</button>\n<div id=\\\"editor\\\">{}</div>\n<div id=\\\"result\\\"></div>\n</div>\", escape(source))\n}\n\nfn escape(source: &str) -> String {\n let mut s = String::new();\n\n for chr in source.trim().chars() {\n match chr {\n '$' => s.push_str(\"$\"),\n '*' => s.push_str(\"*\"),\n '<' => s.push_str(\"<\"),\n '>' => s.push_str(\">\"),\n '\\\\' => s.push_str(\"\\"),\n '_' => s.push_str(\"_\"),\n '`' => s.push_str(\"`\"),\n chr => s.push(chr),\n }\n }\n\n s\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an XFAILed test for if expressions resulting in boxes\n"
},
{
"from": "gpt",
"value": "// xfail-boot\n// xfail-stage0\n// -*- rust -*-\n\n// Tests for if as expressions returning boxed types\n\nfn test_box() {\n auto res = if (true) { @100 } else { @101 };\n check (*res == 100);\n}\n\nfn main() {\n test_box();\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": " Test that object bounds are preferred over global where clause bounds\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\n// run-pass\n// Check that the object bound dyn A + 'a: A is preferred over the\n// where clause bound dyn A + 'static: A.\n\n#![allow(unused)]\n\ntrait A {\n fn test(&self);\n}\n\nfn foo(x: &dyn A)\nwhere\n dyn A + 'static: A, // Using this bound would lead to a lifetime error.\n{\n x.test();\n}\n\nfn main () {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add run-pass test for paths containing the NUL character\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 std::fs;\nuse std::io;\n\nfn assert_invalid_input<T>(on: &str, result: io::Result<T>) {\n fn inner(on: &str, result: io::Result<()>) {\n match result {\n Ok(()) => panic!(\"{} didn't return an error on a path with NUL\", on),\n Err(e) => assert!(e.kind() == io::ErrorKind::InvalidInput,\n \"{} returned a strange {:?} on a path with NUL\", on, e.kind()),\n }\n }\n inner(on, result.map(|_| ()))\n}\n\nfn main() {\n assert_invalid_input(\"File::open\", fs::File::open(\"\\0\"));\n assert_invalid_input(\"File::create\", fs::File::create(\"\\0\"));\n assert_invalid_input(\"remove_file\", fs::remove_file(\"\\0\"));\n assert_invalid_input(\"metadata\", fs::metadata(\"\\0\"));\n assert_invalid_input(\"symlink_metadata\", fs::symlink_metadata(\"\\0\"));\n assert_invalid_input(\"rename1\", fs::rename(\"\\0\", \"a\"));\n assert_invalid_input(\"rename2\", fs::rename(\"a\", \"\\0\"));\n assert_invalid_input(\"copy1\", fs::copy(\"\\0\", \"a\"));\n assert_invalid_input(\"copy2\", fs::copy(\"a\", \"\\0\"));\n assert_invalid_input(\"hard_link1\", fs::hard_link(\"\\0\", \"a\"));\n assert_invalid_input(\"hard_link2\", fs::hard_link(\"a\", \"\\0\"));\n assert_invalid_input(\"soft_link1\", fs::soft_link(\"\\0\", \"a\"));\n assert_invalid_input(\"soft_link2\", fs::soft_link(\"a\", \"\\0\"));\n assert_invalid_input(\"read_link\", fs::read_link(\"\\0\"));\n assert_invalid_input(\"canonicalize\", fs::canonicalize(\"\\0\"));\n assert_invalid_input(\"create_dir\", fs::create_dir(\"\\0\"));\n assert_invalid_input(\"create_dir_all\", fs::create_dir_all(\"\\0\"));\n assert_invalid_input(\"remove_dir\", fs::remove_dir(\"\\0\"));\n assert_invalid_input(\"remove_dir_all\", fs::remove_dir_all(\"\\0\"));\n assert_invalid_input(\"read_dir\", fs::read_dir(\"\\0\"));\n assert_invalid_input(\"set_permissions\",\n fs::set_permissions(\"\\0\", fs::metadata(\".\").unwrap().permissions()));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test for cross-crate const in match pattern.\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\n// xfail-fast\n// aux-build:cci_const.rs\n\nextern mod cci_const;\n\nfn main() {\n let x = cci_const::uint_val;\n match x {\n cci_const::uint_val => {}\n _ => {}\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix stage 0 and 1 tests broken because i128 doesn't work in stages less than 2\n\nBroken by https://github.com/rust-lang/rust/pull/38992.\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#![feature(i128_type)]\n\nfn main() {\n let _ = -0x8000_0000_0000_0000_0000_0000_0000_0000i128;\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#![feature(i128_type)]\n\n// SNAP: run on all stages after snapshot, i128 currently doesn't work on stages 0 and 1\n// ignore-stage1\n// ignore-stage0\n\nfn main() {\n let _ = -0x8000_0000_0000_0000_0000_0000_0000_0000i128;\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Reduce size of array in test case to 1MB\n"
},
{
"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\n// Makes sure that zero-initializing large types is reasonably fast,\n// Doing it incorrectly causes massive slowdown in LLVM during\n// optimisation.\n\n#![feature(intrinsics)]\n\nextern \"rust-intrinsic\" {\n pub fn init<T>() -> T;\n}\n\nconst SIZE: usize = 512 * 1024 * 1024;\n\nfn main() {\n let _memory: [u8; SIZE] = unsafe { init() };\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\n// Makes sure that zero-initializing large types is reasonably fast,\n// Doing it incorrectly causes massive slowdown in LLVM during\n// optimisation.\n\n#![feature(intrinsics)]\n\nextern \"rust-intrinsic\" {\n pub fn init<T>() -> T;\n}\n\nconst SIZE: usize = 1024 * 1024;\n\nfn main() {\n let _memory: [u8; SIZE] = unsafe { init() };\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for concurrently using an FFT object\n"
},
{
"from": "gpt",
"value": "//! Test that we can use an `FFT` object from multiple threads\n\nextern crate rustfft;\n\nuse std::thread;\n\nuse rustfft::FFTplanner;\nuse rustfft::num_complex::Complex32;\n\n#[test]\nfn two_threads() {\n let inverse = false;\n let mut planner = FFTplanner::new(inverse);\n let fft = planner.plan_fft(100);\n\n let threads: Vec<thread::JoinHandle<_>> = (0..2).map(|_| {\n let fft_copy = fft.clone();\n thread::spawn(move || {\n let mut signal = vec![Complex32::new(0.0, 0.0); 100];\n let mut spectrum = vec![Complex32::new(0.0, 0.0); 100];\n fft_copy.process(&mut signal, &mut spectrum);\n })\n }).collect();\n\n for thread in threads {\n thread.join().unwrap();\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add initial Firefix tab opener rust program (0.9)\n"
},
{
"from": "gpt",
"value": "extern mod extra;\n\nuse std::from_str::from_str;\nuse std::io::net::ip::SocketAddr;\nuse std::io::net::tcp::TcpListener;\nuse std::io::{Acceptor,Listener};\nuse std::run::{Process,ProcessOptions};\n\nuse extra::url::Url;\n\n\nfn main() {\n let address = \"127.0.0.1:7777\";\n let addr: SocketAddr = from_str(address).expect(format!(\"Invalid address: {}\", address));\n let listener = TcpListener::bind(addr).expect(format!(\"Failed to bind to: {}\", address));\n let mut acceptor = listener.listen().expect(\"Could not listen\");\n loop {\n let mut tcpStream = acceptor.accept().expect(\"Could not accept connection\");\n let message = tcpStream.read_to_str();\n for line in message.lines() {\n // println!(\"Got message: {}\", line);\n let url: Option<Url> = from_str(line);\n match url {\n None => { println(\"No Url found\") }\n Some(u) => {\n // println!(\"Found Url in: {}\", line);\n if checkUrl(&u) {\n spawnProcess(&u, \"firefox\")\n }\n }\n }\n }\n }\n}\n\nfn checkUrl(u: &Url) -> bool {\n (u.scheme == ~\"http\" || u.scheme == ~\"https\" )\n && u.host != ~\"\"\n}\n\nfn spawnProcess(u: &Url, command: &'static str) {\n // println!(\"{} {}\", command, u.to_str());\n let pOptions = ProcessOptions::new();\n let mut child = Process::new(command, [u.to_str()], pOptions).expect(\"Could not fork process\");\n child.finish();\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an implementation for SimDev.\n\nSigned-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>\n"
},
{
"from": "gpt",
"value": "// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nuse std::fmt;\n\nuse std::path::Path;\nuse std::path::PathBuf;\n\nuse rand::Rng;\nuse rand::ThreadRng;\nuse rand::thread_rng;\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n/// A list of very basic states a SimDev can be in.\npub enum State {\n OK,\n FAILED,\n}\n\n#[derive(Clone)]\n/// A simulated device.\npub struct SimDev {\n pub name: PathBuf,\n rng: ThreadRng,\n pub state: State,\n}\n\n/// Implement Debug for SimDev explicitly as ThreadRng does not derive it.\n/// See: https://github.com/rust-lang-nursery/rand/issues/118\nimpl fmt::Debug for SimDev {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{{SimDev {:?} {:?}\", self.name, self.state)\n }\n}\n\n\nimpl SimDev {\n /// Generates a new device from any path.\n pub fn new_dev(name: &Path) -> Box<SimDev> {\n Box::new(SimDev {\n name: name.to_owned(),\n rng: thread_rng(),\n state: State::OK,\n })\n }\n\n /// Function that causes self to progress probabilistically to a new state.\n pub fn update(&mut self) {\n if self.rng.gen_weighted_bool(8) {\n self.state = State::FAILED;\n }\n }\n\n /// Checks usability of a SimDev\n pub fn usable(&self) -> bool {\n self.state == State::OK\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression test for const prop\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\n// must-compile-successfully\n\n// if `X` were used instead of `x`, `X - 10` would result in a lint.\n// This file should never produce a lint, no matter how the const\n// propagator is improved.\n\n#![deny(warnings)]\n\nconst X: u32 = 5;\n\nfn main() {\n let x = X;\n if x > 10 {\n println!(\"{}\", x - 10);\n } else {\n println!(\"{}\", 10 - x);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove unused import of log crate\n"
},
{
"from": "human",
"value": "//\n// imag - the personal information management suite for the commandline\n// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; version\n// 2.1 of the License.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n//\n\n#![deny(\n dead_code,\n non_camel_case_types,\n non_snake_case,\n path_statements,\n trivial_numeric_casts,\n unstable_features,\n unused_allocation,\n unused_import_braces,\n unused_imports,\n unused_must_use,\n unused_mut,\n unused_qualifications,\n while_true,\n)]\n\n#[macro_use] extern crate log;\nextern crate glob;\nextern crate toml;\n\nextern crate libimagstore;\nextern crate libimagrt;\n#[macro_use] extern crate libimagerror;\nextern crate libimagentryedit;\n\npub mod error;\npub mod builtin;\npub mod result;\npub mod viewer;\n\n"
},
{
"from": "gpt",
"value": "//\n// imag - the personal information management suite for the commandline\n// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors\n//\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; version\n// 2.1 of the License.\n//\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n//\n\n#![deny(\n dead_code,\n non_camel_case_types,\n non_snake_case,\n path_statements,\n trivial_numeric_casts,\n unstable_features,\n unused_allocation,\n unused_import_braces,\n unused_imports,\n unused_must_use,\n unused_mut,\n unused_qualifications,\n while_true,\n)]\n\nextern crate glob;\nextern crate toml;\n\nextern crate libimagstore;\nextern crate libimagrt;\n#[macro_use] extern crate libimagerror;\nextern crate libimagentryedit;\n\npub mod error;\npub mod builtin;\npub mod result;\npub mod viewer;\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Reduce number of threads in many_threads() test\n\nReduce number of threads in many_threads() test to 1k because os x\nfailed to allocate 10k threads\n"
},
{
"from": "human",
"value": "extern crate futures;\n\nuse std::thread;\nuse futures::sync::oneshot;\nuse futures::Future;\nuse futures::future::IntoShared;\n\n\nfn send_shared_oneshot_and_wait_on_multiple_threads(threads_number: u32) {\n let (tx, rx) = oneshot::channel::<u32>();\n let f = rx.shared();\n let mut cloned_futures_waited_oneshots = vec![];\n for _ in 0..threads_number {\n let cloned_future = f.clone();\n let (tx2, rx2) = oneshot::channel::<()>();\n cloned_futures_waited_oneshots.push(rx2);\n thread::spawn(move || {\n assert!(*cloned_future.wait().unwrap() == 6);\n tx2.complete(());\n });\n }\n tx.complete(6);\n for f in cloned_futures_waited_oneshots {\n f.wait().unwrap();\n }\n}\n\n#[test]\nfn one_threads() {\n send_shared_oneshot_and_wait_on_multiple_threads(2);\n}\n\n#[test]\nfn two_threads() {\n send_shared_oneshot_and_wait_on_multiple_threads(2);\n}\n\n#[test]\nfn many_threads() {\n send_shared_oneshot_and_wait_on_multiple_threads(10000);\n}\n"
},
{
"from": "gpt",
"value": "extern crate futures;\n\nuse std::thread;\nuse futures::sync::oneshot;\nuse futures::Future;\nuse futures::future::IntoShared;\n\n\nfn send_shared_oneshot_and_wait_on_multiple_threads(threads_number: u32) {\n let (tx, rx) = oneshot::channel::<u32>();\n let f = rx.shared();\n let mut cloned_futures_waited_oneshots = vec![];\n for _ in 0..threads_number {\n let cloned_future = f.clone();\n let (tx2, rx2) = oneshot::channel::<()>();\n cloned_futures_waited_oneshots.push(rx2);\n thread::spawn(move || {\n assert!(*cloned_future.wait().unwrap() == 6);\n tx2.complete(());\n });\n }\n tx.complete(6);\n for f in cloned_futures_waited_oneshots {\n f.wait().unwrap();\n }\n}\n\n#[test]\nfn one_threads() {\n send_shared_oneshot_and_wait_on_multiple_threads(2);\n}\n\n#[test]\nfn two_threads() {\n send_shared_oneshot_and_wait_on_multiple_threads(2);\n}\n\n#[test]\nfn many_threads() {\n send_shared_oneshot_and_wait_on_multiple_threads(1000);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add linked_list implementation in Rust\n"
},
{
"from": "gpt",
"value": "use List::{Item, Nil};\n\n// linked list implementation in rust\n\nfn main() {\n let mut list = List::new();\n list = list.prepend(1);\n list = list.prepend(2);\n list = list.prepend(3);\n list = list.prepend(4);\n\n println!(\"len of final linked list {}\", list.len());\n println!(\"{}\", list.stringify());\n}\n\nenum List {\n Item(u32, Box<List>),\n Nil,\n}\n\nimpl List {\n fn new() -> List {\n Nil\n }\n fn prepend(self, elem: u32) -> List {\n Item(elem, Box::new(self))\n }\n fn len(&self) -> u32 {\n match *self {\n Item(_, ref tail) => 1 + tail.len(),\n Nil => 0\n }\n }\n fn stringify(&self) -> String {\n match *self {\n Item(head, ref tail) => {\n format!(\"{}, {}\", head, tail.stringify())\n },\n Nil => {\n format!(\"Nil\")\n }\n }\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add address stability test for matches\n"
},
{
"from": "gpt",
"value": "// Check that `ref mut` variables don't change address between the match guard\n// and the arm expression.\n\n// run-pass\n\n#![feature(nll, bind_by_move_pattern_guards)]\n\n// Test that z always point to the same temporary.\nfn referent_stability() {\n let p;\n match 0 {\n ref mut z if { p = z as *const _; true } => assert_eq!(p, z as *const _),\n _ => unreachable!(),\n };\n}\n\n// Test that z is always effectively the same variable.\nfn variable_stability() {\n let p;\n match 0 {\n ref mut z if { p = &z as *const _; true } => assert_eq!(p, &z as *const _),\n _ => unreachable!(),\n };\n}\n\n// Test that a borrow of *z can cross from the guard to the arm.\nfn persist_borrow() {\n let r;\n match 0 {\n ref mut z if { r = z as &_; true } => assert_eq!(*r, 0),\n _ => unreachable!(),\n }\n}\n\nfn main() {\n referent_stability();\n variable_stability();\n persist_borrow();\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test case for labeled break in const assignment\n\nSee https://github.com/rust-lang/rust/issues/51350 for more information.\n"
},
{
"from": "gpt",
"value": "// Using labeled break in a while loop has caused an illegal instruction being\n// generated, and an ICE later.\n//\n// See https://github.com/rust-lang/rust/issues/51350 for more information.\n\nconst CRASH: () = 'a: while break 'a {};\n\nfn main() {\n println!(\"{:?}\", CRASH);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add the example as an example test program.\n\nPutting it in the examples directory makes it be automatically built as\npart of `cargo test`.\n"
},
{
"from": "gpt",
"value": "extern crate wasmparser;\n\nuse std::io;\nuse std::io::prelude::*;\nuse std::fs::File;\nuse std::str;\nuse wasmparser::Parser;\nuse wasmparser::ParserState;\n\nfn get_name(bytes: &[u8]) -> &str {\n str::from_utf8(bytes).ok().unwrap()\n}\n\nfn main() {\n let ref buf: Vec<u8> = read_wasm().unwrap();\n let mut parser = Parser::new(buf);\n loop {\n let state = parser.read();\n if state.is_none() {\n break;\n }\n match *state.unwrap() {\n ParserState::BeginWasm(_, _) => {\n println!(\"====== Module\");\n },\n ParserState::ExportSectionEntry(field, ref ty, _) => {\n println!(\" Export {} {:?}\", get_name(field), ty);\n },\n ParserState::ImportSectionEntry(module, field, _) => {\n println!(\" Import {}::{}\", get_name(module), get_name(field))\n }\n _ => ( /* println!(\" Other {:?}\", state); */ )\n }\n }\n}\n\nfn read_wasm() -> io::Result<Vec<u8>> {\n let mut data = Vec::new();\n let mut f = File::open(\"tests/spec.wasm\")?;\n f.read_to_end(&mut data)?;\n Ok(data)\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for memory layout information\n"
},
{
"from": "gpt",
"value": "// @has type_layout/struct.Foo.html 'Size: '\n// @has - ' bytes'\npub struct Foo {\n pub a: usize,\n b: Vec<String>,\n}\n\n// @has type_layout/enum.Bar.html 'Size: '\n// @has - ' bytes'\npub enum Bar<'a> {\n A(String),\n B(&'a str, (std::collections::HashMap<String, usize>, Foo)),\n}\n\n// @has type_layout/union.Baz.html 'Size: '\n// @has - ' bytes'\npub union Baz {\n a: &'static str,\n b: usize,\n c: &'static [u8],\n}\n\n// @has type_layout/struct.X.html 'Size: '\n// @has - ' bytes'\npub struct X(usize);\n\n// @has type_layout/struct.Y.html 'Size: '\n// @has - ' byte'\n// @!has - ' bytes'\npub struct Y(u8);\n\n// @!has type_layout/struct.Generic.html 'Size: '\npub struct Generic<T>(T);\n\n// @has type_layout/struct.Unsized.html 'Size: '\n// @has - '(unsized)'\npub struct Unsized([u8]);\n\n// @!has type_layout/type.TypeAlias.html 'Size: '\npub type TypeAlias = X;\n\n// @!has type_layout/trait.MyTrait.html 'Size: '\npub trait MyTrait {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for rustdoc ignore test\n\nThis will check for regression on issue #32556\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/// Blah blah blah\n/// ``` ignore\n/// bad_assert!();\n/// ```\npub fn foo() {}\n\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test of serialize_trait_object involving generics\n"
},
{
"from": "gpt",
"value": "use erased_serde::serialize_trait_object;\n\npub trait MyTrait: erased_serde::Serialize {}\n\nserialize_trait_object!(MyTrait);\n\npub trait MyGenericTrait<'a, T>: erased_serde::Serialize {}\n\nserialize_trait_object!(<'a, T> MyGenericTrait<'a, T>);\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add a test case for self regions and typeclass implementations\n"
},
{
"from": "gpt",
"value": "type clam = { chowder: &int };\n\nimpl clam for clam {\n fn get_chowder() -> &self.int { ret self.chowder; }\n}\n\nfn main() {\n let clam = { chowder: &3 };\n log(debug, *clam.get_chowder());\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test that unique boxes in vectors are copied when the vector is\n\nIssue #409\n"
},
{
"from": "gpt",
"value": "fn main() {\n let a = [~mutable 10];\n let b = a;\n\n assert *a[0] == 10;\n assert *b[0] == 10;\n\n // This should only modify the value in a, not b\n *a[0] = 20;\n\n assert *a[0] == 20;\n assert *b[0] == 10;\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add example for multiple simultaneous examples\n"
},
{
"from": "gpt",
"value": "extern crate init = \"gl-init-rs\";\nextern crate libc;\nextern crate gl;\n\nfn main() {\n let window1 = init::Window::new().unwrap();\n let window2 = init::Window::new().unwrap();\n\n spawn(proc() {\n run(window1, (0.0, 1.0, 0.0, 1.0));\n });\n\n spawn(proc() {\n run(window2, (0.0, 0.0, 1.0, 1.0));\n });\n}\n\nfn run(window: init::Window, color: (f32, f32, f32, f32)) {\n unsafe { window.make_current() };\n\n gl::load_with(|symbol| window.get_proc_address(symbol) as *const libc::c_void);\n\n gl::ClearColor(color.val0(), color.val1(), color.val2(), color.val3());\n\n while !window.is_closed() {\n window.wait_events().collect::<Vec<init::Event>>();\n\n gl::Clear(gl::COLOR_BUFFER_BIT);\n\n window.swap_buffers();\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add failing test for globals to subcommands\n\nIssue 978 mentions that subcommands cannot see the value\nof globals that get passed, even if ArgSettings::PropagateGlobalsDown\nis true.\n\nThis change commits a failing test that reproduces this error.\n"
},
{
"from": "gpt",
"value": "extern crate clap;\nextern crate regex;\n\ninclude!(\"../clap-test.rs\");\n\nuse clap::{App, Arg, SubCommand, ErrorKind, AppSettings};\n\nstatic VISIBLE_ALIAS_HELP: &'static str = \"clap-test 2.6\n\nUSAGE:\n clap-test [SUBCOMMAND]\n\nFLAGS:\n -h, --help Prints help information\n -V, --version Prints version information\n\nSUBCOMMANDS:\n help Prints this message or the help of the given subcommand(s)\n test Some help [aliases: dongle, done]\";\n\nstatic INVISIBLE_ALIAS_HELP: &'static str = \"clap-test 2.6\n\nUSAGE:\n clap-test [SUBCOMMAND]\n\nFLAGS:\n -h, --help Prints help information\n -V, --version Prints version information\n\nSUBCOMMANDS:\n help Prints this message or the help of the given subcommand(s)\n test Some help\";\n\n#[cfg(feature = \"suggestions\")]\nstatic DYM: &'static str = \"error: The subcommand 'subcm' wasn't recognized\n\\tDid you mean 'subcmd'?\n\nIf you believe you received this message in error, try re-running with 'clap-test -- subcm'\n\nUSAGE:\n clap-test [FLAGS] [OPTIONS] [ARGS] [SUBCOMMAND]\n\nFor more information try --help\";\n\n#[cfg(feature = \"suggestions\")]\nstatic DYM2: &'static str = \"error: Found argument '--subcm' which wasn't expected, or isn't valid in this context\n\\tDid you mean to put '--subcmdarg' after the subcommand 'subcmd'?\n\nUSAGE:\n clap-test [FLAGS] [OPTIONS] [ARGS] [SUBCOMMAND]\n\nFor more information try --help\";\n\n#[test]\nfn subcommand_can_access_global_arg_if_setting_is_on() {\n let global_arg = Arg::with_name(\"GLOBAL_ARG\")\n .long(\"global-arg\")\n .help(\n \"Specifies something needed by the subcommands\",\n )\n .global(true)\n .takes_value(true);\n \n let double_sub_command = SubCommand::with_name(\"outer\")\n .subcommand(SubCommand::with_name(\"run\"));\n\n let matches = App::new(\"globals\")\n .setting(AppSettings::PropagateGlobalValuesDown)\n .arg(global_arg)\n .subcommand(double_sub_command)\n .get_matches_from(\n vec![\"globals\", \"outer\", \"--global-arg\", \"some_value\"]\n );\n\n let sub_match = matches.subcommand_matches(\"outer\").expect(\"could not access subcommand\");\n\n assert_eq!(sub_match.value_of(\"global-arg\").expect(\"subcommand could not access global arg\"), \n \"some_value\", \"subcommand did not have expected value for global arg\");\n\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an unwind test for failure during unique box construction\n"
},
{
"from": "gpt",
"value": "// error-pattern:fail\n\nfn f() -> [int] { fail; }\n\n// Voodoo. In unwind-alt we had to do this to trigger the bug. Might\n// have been to do with memory allocation patterns.\nfn prime() {\n @0;\n}\n\nfn partial() {\n let x = ~f();\n}\n\nfn main() {\n prime();\n partial();\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add basic program for benchmarking decode speed\n"
},
{
"from": "gpt",
"value": "// Claxon -- A FLAC decoding library in Rust\n// Copyright 2016 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#![feature(test)]\n\nextern crate claxon;\nextern crate test;\n\nuse std::env;\nuse std::path::Path;\nuse std::fs::File;\nuse std::io::{Cursor, Read};\nuse claxon::FlacReader;\n\n/// Reads a file into memory entirely.\nfn read_file<P: AsRef<Path>>(path: P) -> Vec<u8> {\n let mut file = File::open(path).unwrap();\n let mut data = Vec::new();\n file.read_to_end(&mut data).unwrap();\n data\n}\n\n/// Decode a file into 16-bit integers.\n///\n/// This consumes the decoded samples into a black box.\nfn decode_file_i16(data: &[u8]) {\n let cursor = Cursor::new(data);\n let mut reader = FlacReader::new(cursor).unwrap();\n\n let bps = reader.streaminfo().bits_per_sample as u64;\n assert!(bps < 8 * 16);\n\n for sample in reader.samples::<i16>() {\n test::black_box(sample.unwrap());\n }\n}\n\nfn main() {\n let bits = env::args().nth(1).expect(\"no bit depth given\");\n let fname = env::args().nth(2).expect(\"no file given\");\n\n let data = read_file(fname);\n if bits == \"16\" {\n // TODO: Do several passes and report timing information.\n decode_file_i16(&data);\n } else if bits == \"32\" {\n // TODO\n } else {\n panic!(\"expected bit depth of 16 or 32\");\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for a mixture of arguments\n"
},
{
"from": "gpt",
"value": "extern crate clap;\n\nuse clap::{App, Arg};\n\n#[test]\nfn mixed_positional_and_options() {\n App::new(\"mixed_positional_and_options\")\n .arg(Arg::with_name(\"feed\")\n .short(\"f\")\n .long(\"feed\")\n .takes_value(true)\n .multiple(true))\n .arg(Arg::with_name(\"config\")\n .required(true)\n .index(1))\n .get_matches_from(vec![\"\", \"--feed\", \"1\", \"config.toml\"]);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a compile-fail test for qualification lint\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\n#[deny(unnecessary_qualification)];\n\nmod foo {\n pub fn bar() {}\n}\n\nfn main() {\n use foo::bar;\n foo::bar(); //~ ERROR: unnecessary qualification\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression test for lint deprecation\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// Check that lint deprecation works\n\n#[deny(unused_variable)] //~ warning: lint unused_variable has been renamed to unused_variables\npub fn main() {\n let x = 0u8; //~ error: unused variable:\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "needless_continue: Add tests for helper functions to the needless_continue lint.\n\nCreating a test file per function sounds a bit excessive, so just\nclubbing all needless_continue specific function tests into this module.\n"
},
{
"from": "gpt",
"value": "// Tests for the various helper functions used by the needless_continue\n// lint that don't belong in utils.\nextern crate clippy_lints;\nuse clippy_lints::needless_continue::{erode_from_back, erode_block, erode_from_front};\n\n#[test]\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn test_erode_from_back() {\n let input = \"\\\n{\n let x = 5;\n let y = format!(\\\"{}\\\", 42);\n}\";\n\n let expected = \"\\\n{\n let x = 5;\n let y = format!(\\\"{}\\\", 42);\";\n\n let got = erode_from_back(input);\n assert_eq!(expected, got);\n}\n\n#[test]\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn test_erode_from_back_no_brace() {\n let input = \"\\\nlet x = 5;\nlet y = something();\n\";\n let expected = \"\";\n let got = erode_from_back(input);\n assert_eq!(expected, got);\n}\n\n#[test]\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn test_erode_from_front() {\n let input = \"\n {\n something();\n inside_a_block();\n }\n \";\n let expected =\n\" something();\n inside_a_block();\n }\n \";\n let got = erode_from_front(input);\n println!(\"input: {}\\nexpected:\\n{}\\ngot:\\n{}\", input, expected, got);\n assert_eq!(expected, got);\n}\n\n#[test]\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn test_erode_from_front_no_brace() {\n let input = \"\n something();\n inside_a_block();\n \";\n let expected =\n\"something();\n inside_a_block();\n \";\n let got = erode_from_front(input);\n println!(\"input: {}\\nexpected:\\n{}\\ngot:\\n{}\", input, expected, got);\n assert_eq!(expected, got);\n}\n\n\n#[test]\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn test_erode_block() {\n\n let input = \"\n {\n something();\n inside_a_block();\n }\n \";\n let expected =\n\" something();\n inside_a_block();\";\n let got = erode_block(input);\n println!(\"input: {}\\nexpected:\\n{}\\ngot:\\n{}\", input, expected, got);\n assert_eq!(expected, got);\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for drop for newtype structs.\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\n// Make sure the destructor is run for newtype structs.\n\nstruct Foo(@mut int);\n\n#[unsafe_destructor]\nimpl Drop for Foo {\n fn finalize(&self) {\n ***self = 23;\n }\n}\n\nfn main() {\n let y = @mut 32;\n {\n let x = Foo(y);\n }\n assert_eq!(*y, 23);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add example of color effects\n"
},
{
"from": "gpt",
"value": "//! Demonstrates adding a color tint and applying a color gradient to a grayscale image.\n\nextern crate image;\nextern crate imageproc;\n\nuse std::env;\nuse std::path::Path;\nuse image::{Luma, open, Rgb};\nuse imageproc::map::map_colors;\nuse imageproc::pixelops::weighted_sum;\n\n/// Tint a grayscale value with the given color.\n/// Midtones are tinted most heavily.\npub fn tint(gray: Luma<u8>, color: Rgb<u8>) -> Rgb<u8> {\n let dist_from_mid = ((gray[0] as f32 - 128f32).abs()) / 255f32;\n let scale_factor = 1f32 - 4f32 * dist_from_mid.powi(2);\n weighted_sum(Rgb([gray[0]; 3]), color, 1.0, scale_factor)\n}\n\n/// Linearly interpolates between low and mid colors for pixel intensities less than\n/// half of maximum brightness and between mid and high for those above.\npub fn color_gradient(gray: Luma<u8>, low: Rgb<u8>, mid: Rgb<u8>, high: Rgb<u8>) -> Rgb<u8> {\n let fraction = gray[0] as f32 / 255f32;\n let (lower, upper, offset) = if fraction < 0.5 { (low, mid, 0.0) } else { (mid, high, 0.5) };\n let right_weight = 2.0 * (fraction - offset);\n let left_weight = 1.0 - right_weight;\n weighted_sum(lower, upper, left_weight, right_weight)\n}\n\nfn main() {\n\n let arg = if env::args().count() == 2 {\n env::args().nth(1).unwrap()\n } else {\n panic!(\"Please enter an input file\")\n };\n let path = Path::new(&arg);\n\n // Load a image::DynamicImage and convert it to a image::GrayImage\n let image = open(path)\n .ok()\n .expect(&format!(\"Could not load image at {:?}\", path))\n .to_luma();\n\n let blue = Rgb([0u8, 0u8, 255u8]);\n\n // Apply the color tint to every pixel in the grayscale image, producing a image::RgbImage\n let tinted = map_colors(&image, |pix| tint(pix, blue));\n let _ = tinted.save(path.with_file_name(\"tinted.png\")).unwrap();\n\n // Apply color gradient to each image pixel\n let black = Rgb([0u8, 0u8, 0u8]);\n let red = Rgb([255u8, 0u8, 0u8]);\n let yellow = Rgb([255u8, 255u8, 0u8]);\n let gradient = map_colors(&image, |pix| color_gradient(pix, black, red, yellow));\n let _ = gradient.save(path.with_file_name(\"gradient.png\")).unwrap();\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix merge after reexport fix\n"
},
{
"from": "human",
"value": "use std::io::{Result, SeekFrom};\nuse std::syscall::*;\nuse std::Url;\n\npub struct Resource;\n\nimpl Resource {\n pub fn dup(&self) -> Result<Box<Resource>> {\n Ok(box Resource)\n }\n\n pub fn path(&self) -> Result<String> {\n Ok(format!(\"\"))\n }\n\n pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {\n Ok(0)\n }\n\n pub fn write(&mut self, buf: &[u8]) -> Result<usize> {\n Ok(0)\n }\n\n pub fn seek(&mut self, _: SeekFrom) -> Result<u64> {\n Err(SysError::new(ESPIPE))\n }\n\n pub fn sync(&mut self) -> Result<()> {\n Ok(())\n }\n}\n\npub struct Scheme;\n\nimpl Scheme {\n pub fn new() -> Box<Scheme> {\n box Scheme\n }\n\n pub fn open(&mut self, url_str: &str, _: usize) -> Result<Box<Resource>> {\n Err(SysError::new(ENOENT))\n }\n}\n"
},
{
"from": "gpt",
"value": "use std::io::{Result, SeekFrom};\nuse std::syscall::*;\nuse std::url::Url;\n\npub struct Resource;\n\nimpl Resource {\n pub fn dup(&self) -> Result<Box<Resource>> {\n Ok(box Resource)\n }\n\n pub fn path(&self) -> Result<String> {\n Ok(format!(\"\"))\n }\n\n pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {\n Ok(0)\n }\n\n pub fn write(&mut self, buf: &[u8]) -> Result<usize> {\n Ok(0)\n }\n\n pub fn seek(&mut self, _: SeekFrom) -> Result<u64> {\n Err(SysError::new(ESPIPE))\n }\n\n pub fn sync(&mut self) -> Result<()> {\n Ok(())\n }\n}\n\npub struct Scheme;\n\nimpl Scheme {\n pub fn new() -> Box<Scheme> {\n box Scheme\n }\n\n pub fn open(&mut self, url_str: &str, _: usize) -> Result<Box<Resource>> {\n Err(SysError::new(ENOENT))\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for BTreeMap lifetime bound to see if it compiles\n"
},
{
"from": "gpt",
"value": "// check-pass\n\nuse std::collections::{BTreeMap, HashMap};\n\ntrait Map\nwhere\n for<'a> &'a Self: IntoIterator<Item = (&'a Self::Key, &'a Self::Value)>,\n{\n type Key;\n type Value;\n}\n\nimpl<K, V> Map for HashMap<K, V> {\n type Key = K;\n type Value = V;\n}\n\nimpl<K, V> Map for BTreeMap<K, V> {\n type Key = K;\n type Value = V;\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for wrong code generation for HashSet creation on arm cpu\n\nThis is test for #42918.\nTo reproduce bug you need machine with arm cpu and compile with optimization.\nI tried with rustc 1.19.0-nightly (3d5b8c626 2017-06-09),\nif compile test with -C opt-level=3 for target=arm-linux-androideabi\nand run on \"Qualcomm MSM 8974 arm cpu\" then assert fails,\nif compile and run with -C opt-level=2 it gives segmentation fault.\nSo I add `compile-flags: -O`.\nWith rustc 1.19.0 (0ade33941 2017-07-17) all works fine.\nCloses #42918\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// compile-flags: -O\n\nuse std::collections::HashSet;\n\n#[derive(PartialEq, Debug, Hash, Eq, Clone, PartialOrd, Ord)]\nenum MyEnum {\n E0,\n\n E1,\n\n E2,\n E3,\n E4,\n\n E5,\n E6,\n E7,\n}\n\n\nfn main() {\n use MyEnum::*;\n let s: HashSet<_> = [E4, E1].iter().cloned().collect();\n let mut v: Vec<_> = s.into_iter().collect();\n v.sort();\n\n assert_eq!([E1, E4], &v[..]);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for reading truncated files\n\nTests loading every image for every truncation length up to 1000\nbytes. Expensive, so ignored by default.\n"
},
{
"from": "gpt",
"value": "//! Ensure truncated images are read without panics.\n\nuse std::fs;\nuse std::path::PathBuf;\nuse std::io::Read;\n\nextern crate image;\nextern crate glob;\n\nconst BASE_PATH: [&'static str; 2] = [\".\", \"tests\"];\nconst IMAGE_DIR: &'static str = \"images\";\n\nfn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)\nwhere F: Fn(PathBuf) {\n\tlet base: PathBuf = BASE_PATH.iter().collect();\n\tlet decoders = &[\"tga\", \"tiff\", \"png\", \"gif\", \"bmp\", \"ico\", \"jpg\"];\n\tfor decoder in decoders {\n\t\tlet mut path = base.clone();\n\t\tpath.push(dir);\n\t\tpath.push(decoder);\n\t\tpath.push(\"*\");\n\t\tpath.push(\"*.\".to_string() + match input_decoder {\n\t\t\tSome(val) => val,\n\t\t\tNone => decoder\n\t\t});\n\t\tlet pattern = &*format!(\"{}\", path.display());\n\t\tfor path in glob::glob(pattern).unwrap().filter_map(Result::ok) {\n\t\t\tfunc(path)\n\t\t}\n\t}\n}\n\nfn truncate_images(decoder: &str) {\n process_images(IMAGE_DIR, Some(decoder), |path| {\n println!(\"{:?}\", path);\n let fin = fs::File::open(&path).unwrap();\n let max_length = 1000;\n let mut buf = Vec::with_capacity(max_length);\n fin.take(max_length as u64).read_to_end(&mut buf).unwrap();\n for i in 0..buf.len() {\n image::load_from_memory(&buf[..i+1]).ok();\n }\n })\n}\n\n#[test] #[ignore]\nfn truncate_tga() {\n truncate_images(\"tga\")\n}\n\n#[test] #[ignore]\nfn truncate_tiff() {\n truncate_images(\"tiff\")\n}\n\n#[test] #[ignore]\nfn truncate_png() {\n truncate_images(\"png\")\n}\n\n#[test] #[ignore]\nfn truncate_gif() {\n truncate_images(\"gif\")\n}\n\n#[test] #[ignore]\nfn truncate_bmp() {\n truncate_images(\"bmp\")\n}\n\n#[test] #[ignore]\nfn truncate_ico() {\n truncate_images(\"ico\")\n}\n\n#[test] #[ignore]\nfn truncate_jpg() {\n truncate_images(\"jpg\")\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test for (previously uncaught) infinite loop identified by matthewjasper.\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\n// rust-lang/rust#45696: This test checks the compiler won't infinite\n// loop when you declare a variable of type `struct A(Box<A>, ...);`\n// (which is impossible to construct but *is* possible to declare; see\n// also issues #4287, #44933, and #52852).\n//\n// We will explicitly test AST-borrowck, NLL, and migration modes;\n// thus we will also skip the automated compare-mode=nll.\n\n// revisions: ast nll migrate\n// ignore-compare-mode-nll\n\n#![cfg_attr(nll, feature(nll))]\n//[migrate]compile-flags: -Z borrowck=migrate -Z two-phase-borrows\n\n// run-pass\n\n// This test has structs and functions that are by definiton unusable\n// all over the place, so just go ahead and allow dead_code\n#![allow(dead_code)]\n\n// direct regular recursion with indirect ownership via box\nstruct C { field: Box<C> }\n\n// direct non-regular recursion with indirect ownership via box\nstruct D { field: Box<(D, D)> }\n\n// indirect regular recursion with indirect ownership via box.\nstruct E { field: F }\nstruct F { field: Box<E> }\n\n// indirect non-regular recursion with indirect ownership via box.\nstruct G { field: (F, F) }\nstruct H { field: Box<E> }\n\n// These enums are cases that are not currently hit by the\n// `visit_terminator_drop` recursion down a type's structural\n// definition.\n//\n// But it seems prudent to include them in this test as variants on\n// the above, in that they are similarly non-constructable data types\n// with destructors that would diverge.\nenum I { One(Box<I>) }\nenum J { One(Box<J>), Two(Box<J>) }\n\nfn impossible_to_call_c(_c: C) { }\nfn impossible_to_call_d(_d: D) { }\nfn impossible_to_call_e(_e: E) { }\nfn impossible_to_call_f(_f: F) { }\nfn impossible_to_call_g(_g: G) { }\nfn impossible_to_call_h(_h: H) { }\nfn impossible_to_call_i(_i: I) { }\nfn impossible_to_call_j(_j: J) { }\n\nfn main() {\n\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test to ensure const-prop fails gracefully\n"
},
{
"from": "gpt",
"value": "#[inline(never)]\nfn read(_: usize) { }\n\nfn main() {\n const FOO: &i32 = &1;\n let x = FOO as *const i32 as usize;\n read(x);\n}\n\n// END RUST SOURCE\n// START rustc.main.ConstProp.before.mir\n// bb0: {\n// ...\n// _3 = _4;\n// _2 = move _3 as *const i32 (Misc);\n// ...\n// _1 = move _2 as usize (Misc);\n// ...\n// _6 = _1;\n// _5 = const read(move _6) -> bb1;\n// }\n// END rustc.main.ConstProp.before.mir\n// START rustc.main.ConstProp.after.mir\n// bb0: {\n// ...\n// _3 = _4;\n// _2 = move _3 as *const i32 (Misc);\n// ...\n// _1 = move _2 as usize (Misc);\n// ...\n// _6 = _1;\n// _5 = const read(move _6) -> bb1;\n// }\n// END rustc.main.ConstProp.after.mir\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add codegen test for integers compare\n"
},
{
"from": "gpt",
"value": "// This is test for more optimal Ord implementation for integers.\n// See <https://github.com/rust-lang/rust/issues/63758> for more info.\n\n// compile-flags: -C opt-level=3\n\n#![crate_type = \"lib\"]\n\nuse std::cmp::Ordering;\n\n// CHECK-LABEL: @cmp_signed\n#[no_mangle]\npub fn cmp_signed(a: i64, b: i64) -> Ordering {\n// CHECK: icmp slt\n// CHECK: icmp sgt\n// CHECK: zext i1\n// CHECK: select i1\n a.cmp(&b)\n}\n\n// CHECK-LABEL: @cmp_unsigned\n#[no_mangle]\npub fn cmp_unsigned(a: u32, b: u32) -> Ordering {\n// CHECK: icmp ult\n// CHECK: icmp ugt\n// CHECK: zext i1\n// CHECK: select i1\n a.cmp(&b)\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test that column information is not emitted for MSVC targets\n"
},
{
"from": "gpt",
"value": "// Verify that no column information is emitted for MSVC targets\n//\n// only-msvc\n// compile-flags: -C debuginfo=2\n\n// CHECK-NOT: !DILexicalBlock({{.*}}column: {{.*}})\n// CHECK-NOT: !DILocation({{.*}}column: {{.*}})\n\npub fn add(a: u32, b: u32) -> u32 {\n a + b\n}\n\nfn main() {\n let c = add(1, 2);\n println!(\"{}\", c);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add \"cheating\" http server example.\n\nBecause I'm a showoff.\n\n% wrk -t8 -c100 -d10s http://localhost:5555\nRunning 10s test @ http://localhost:5555\n 8 threads and 100 connections\n Thread Stats Avg Stdev Max +/- Stdev\n Latency 5.01s 2.37s 7.98s 69.04%\n Req/Sec 554.67k 582.15k 3.28M 84.58%\n 74197525 requests in 10.39s, 3.66GB read\n Socket errors: connect 0, read 142, write 0, timeout 192\nRequests/sec: 7143230.20\nTransfer/sec: 361.04MB\n"
},
{
"from": "gpt",
"value": "extern crate mioco;\nextern crate env_logger;\n\nuse std::net::SocketAddr;\nuse std::str::FromStr;\nuse std::io::Write;\nuse mioco::mio::tcp::{TcpSocket};\n\nconst DEFAULT_LISTEN_ADDR : &'static str = \"127.0.0.1:5555\";\n\nfn listend_addr() -> SocketAddr {\n FromStr::from_str(DEFAULT_LISTEN_ADDR).unwrap()\n}\n\nconst RESPONSE: &'static str = \"HTTP/1.1 200 OK\\r\nContent-Length: 14\\r\n\\r\nHello World\\r\n\\r\";\n\nfn main() {\n env_logger::init().unwrap();\n let addr = listend_addr();\n\n let sock = TcpSocket::v4().unwrap();\n sock.bind(&addr).unwrap();\n let sock = sock.listen(1024).unwrap();\n\n println!(\"Starting \\\"cheating\\\" http server on {:?}\", sock.local_addr().unwrap());\n\n mioco::start(move |mioco| {\n for _ in 0..8 {\n let sock = try!(sock.try_clone());\n mioco.spawn(move |mioco| {\n let sock = mioco.wrap(sock);\n loop {\n let conn = try!(sock.accept());\n mioco.spawn(move |mioco| {\n let mut conn = mioco.wrap(conn);\n loop {\n let _ = try!(conn.write(&RESPONSE.as_bytes()));\n }\n });\n }\n });\n }\n Ok(())\n });\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add ignored test for associated types in const impl\n"
},
{
"from": "gpt",
"value": "// ignore-test\n\n// FIXME: This test should fail since, within a const impl of `Foo`, the bound on `Foo::Bar` should\n// require a const impl of `Add` for the associated type.\n\n#![allow(incomplete_features)]\n#![feature(const_trait_impl)]\n#![feature(const_fn)]\n\nstruct NonConstAdd(i32);\n\nimpl std::ops::Add for NonConstAdd {\n type Output = Self;\n\n fn add(self, rhs: Self) -> Self {\n NonConstAdd(self.0 + rhs.0)\n }\n}\n\ntrait Foo {\n type Bar: std::ops::Add;\n}\n\nimpl const Foo for NonConstAdd {\n type Bar = NonConstAdd;\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for untagged unions\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\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"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Fix kindck to consider inherited bounds\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// Test that Copy bounds inherited by trait are checked.\n\nuse std::any::Any;\nuse std::any::AnyRefExt;\n\ntrait Foo : Copy {\n}\n\nimpl<T:Copy> Foo for T {\n}\n\nfn take_param<T:Foo>(foo: &T) { }\n\nfn main() {\n let x = box 3i;\n take_param(&x); //~ ERROR does not fulfill `Copy`\n\n let y = &x;\n let z = &x as &Foo; //~ ERROR does not fulfill `Copy`\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add codegen test checking binary_search allows eliding bound checks\n"
},
{
"from": "gpt",
"value": "// min-llvm-version: 11.0.0\n// compile-flags: -O\n// ignore-debug: the debug assertions get in the way\n#![crate_type = \"lib\"]\n\n// Make sure no bounds checks are emitted when slicing or indexing\n// with an index from `binary_search`.\n\n// CHECK-LABEL: @binary_search_index_no_bounds_check\n#[no_mangle]\npub fn binary_search_index_no_bounds_check(s: &[u8]) -> u8 {\n // CHECK-NOT: panic\n // CHECK-NOT: slice_index_len_fail\n if let Ok(idx) = s.binary_search(&b'\\\\') {\n s[idx]\n } else {\n 42\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rather involved run-pass test case.\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// Test associated type references in structure fields.\n\ntrait Test {\n type V;\n\n fn test(&self, value: &Self::V) -> bool;\n}\n\n///////////////////////////////////////////////////////////////////////////\n\nstruct TesterPair<T:Test> {\n tester: T,\n value: T::V,\n}\n\nimpl<T:Test> TesterPair<T> {\n fn new(tester: T, value: T::V) -> TesterPair<T> {\n TesterPair { tester: tester, value: value }\n }\n\n fn test(&self) -> bool {\n self.tester.test(&self.value)\n }\n}\n\n///////////////////////////////////////////////////////////////////////////\n\nstruct EqU32(u32);\nimpl Test for EqU32 {\n type V = u32;\n\n fn test(&self, value: &u32) -> bool {\n self.0 == *value\n }\n}\n\nstruct EqI32(i32);\nimpl Test for EqI32 {\n type V = i32;\n\n fn test(&self, value: &i32) -> bool {\n self.0 == *value\n }\n}\n\nfn main() {\n let tester = TesterPair::new(EqU32(22), 23);\n tester.test();\n\n let tester = TesterPair::new(EqI32(22), 23);\n tester.test();\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression test for Clone for [[T; 256]; 4] where T: Copy and not Clone\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 #30244\n\n#[derive(Copy, Clone)]\nstruct Array {\n arr: [[u8; 256]; 4]\n}\n\npub fn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression test for MIR drop generation in async loops\n\nFixes #61986.\n"
},
{
"from": "gpt",
"value": "// compile-pass\n// edition:2018\n//\n// Tests that we properly handle StorageDead/StorageLives for temporaries\n// created in async loop bodies.\n\n#![feature(async_await)]\n\nasync fn bar() -> Option<()> {\n Some(())\n}\n\nasync fn listen() {\n while let Some(_) = bar().await {\n String::new();\n }\n}\n\nfn main() {\n listen();\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test Hello World Iron server\n"
},
{
"from": "gpt",
"value": "use iron::prelude::*;\nuse iron::status;\n\n/// Test hello world server\npub fn hello_world(_: &mut Request) -> IronResult<Response> {\n Ok(Response::with((status::Ok, \"Hello World!\")))\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add solution to problem 72\n"
},
{
"from": "gpt",
"value": "#![feature(core, step_by)]\n#[macro_use] extern crate libeuler;\n\nuse std::collections::{HashSet, HashMap};\n\nuse libeuler::prime::SieveOfAtkin;\n/// Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is\n/// called a reduced proper fraction.\n///\n/// If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:\n///\n/// 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6,\n/// 6/7, 7/8\n///\n/// It can be seen that there are 21 elements in this set.\n///\n/// How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000?\nfn main() {\n solutions! {\n inputs: (max_denom: u64 = 1_000_000)\n\n sol naive {\n let sieve = SieveOfAtkin::new(max_denom * 2);\n let mut nums = (0..(max_denom+1)).collect::<Vec<u64>>();\n\n let mut result = 0;\n for denom in 2..(max_denom + 1) {\n if nums[denom as usize] == denom {\n for next in (denom..(max_denom + 1)).step_by(denom) {\n nums[next as usize] = nums[next as usize] / denom * (denom - 1);\n }\n }\n\n result += nums[denom as usize];\n }\n\n result\n }\n }\n}\n\nfn load_powers(memo: &mut HashMap<Vec<u64>, HashSet<u64>>, mut factors: Vec<u64>) -> HashSet<u64> {\n if factors.len() == 0 {\n return {\n let mut ret = HashSet::new();\n ret.insert(1);\n ret\n };\n }\n\n if memo.contains_key(&factors) {\n return memo[&factors].clone();\n }\n\n let mut retval = HashSet::new();\n\n let f = factors.clone();\n while factors.len() > 0 {\n let fact = factors.pop().unwrap();\n for pow in load_powers(memo, factors.clone()) {\n retval.insert(pow);\n retval.insert(pow * fact);\n }\n }\n\n memo.insert(f, retval.clone());\n\n retval\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Use of impl trait in an impl as the valoe for an associated type in a dyn\n"
},
{
"from": "gpt",
"value": "// check-pass\n\n#![feature(type_alias_impl_trait)]\n#![allow(dead_code)]\n\ntype Foo = Box<dyn Iterator<Item = impl Send>>;\n\nfn make_foo() -> Foo {\n Box::new(vec![1, 2, 3].into_iter())\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rust code for tournament project\n\nIt passed all testcases\n"
},
{
"from": "gpt",
"value": "use std::collections::HashMap;\nuse std::cmp::Ordering;\n\n\n#[derive(Debug)]\nstruct Record {\n win: u32,\n draw: u32,\n lose: u32,\n}\n\nimpl Record {\n fn new(win: u32, draw: u32, lose: u32) -> Record {\n Record {\n win: win,\n draw: draw,\n lose: lose,\n }\n }\n\n fn win(&mut self) {\n self.win += 1\n }\n\n fn draw(&mut self) {\n self.draw += 1;\n }\n\n fn lose(&mut self) {\n self.lose += 1;\n }\n\n fn matches(&self) -> u32 {\n self.win + self.draw + self.lose\n }\n\n fn scores(&self) -> u32 {\n self.win * 3 + self.draw\n }\n}\n\nfn add_winer(matches: &mut HashMap<String, Record>, team: &str) {\n matches\n .entry(team.to_string())\n .or_insert_with(|| Record::new(0, 0, 0))\n .win();\n}\n\nfn add_loser(matches: &mut HashMap<String, Record>, team: &str) {\n matches\n .entry(team.to_string())\n .or_insert_with(|| Record::new(0, 0, 0))\n .lose();\n}\n\nfn add_drawn(matches: &mut HashMap<String, Record>, team: &str) {\n matches\n .entry(team.to_string())\n .or_insert_with(|| Record::new(0, 0, 0))\n .draw();\n}\n\npub fn tally(input: &str) -> String {\n let mut matches = HashMap::new();\n\n for text in input.lines() {\n let cmd = text.split(';').collect::<Vec<_>>();\n\n match cmd[2] {\n \"win\" => {\n add_winer(&mut matches, cmd[0]);\n add_loser(&mut matches, cmd[1])\n }\n \"draw\" => {\n add_drawn(&mut matches, cmd[0]);\n add_drawn(&mut matches, cmd[1])\n }\n \"loss\" => {\n add_loser(&mut matches, cmd[0]);\n add_winer(&mut matches, cmd[1])\n }\n _ => (),\n };\n }\n\n let mut teams = matches.iter().collect::<Vec<_>>();\n\n teams.sort_by(|&(ateam, ascore), &(bteam, bscore)| {\n let ascores = ascore.scores();\n let bscores = bscore.scores();\n let r = bscores.cmp(&ascores);\n match r {\n Ordering::Equal => ateam.cmp(bteam),\n _ => r,\n }\n });\n\n let mut result = \"Team | MP | W | D | L | P\".to_string();\n for (team, score) in teams {\n result.push('\\n');\n\n result += &format!(\n \"{:30} | {:2} | {:2} | {:2} | {:2} | {:2}\",\n team,\n score.matches(),\n score.win,\n score.draw,\n score.lose,\n score.scores()\n );\n }\n\n result\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for module ambiguity\n"
},
{
"from": "gpt",
"value": "// ignore-tidy-linelength\n\n#![deny(intra_doc_link_resolution_failure)]\n\n\npub fn foo() {\n\n}\n\npub mod foo {}\n// @has intra_doc_link_mod_ambiguity/struct.A.html '//a/@href' '../intra_doc_link_mod_ambiguity/foo/index.html'\n/// Module is [`module@foo`]\npub struct A;\n\n\n// @has intra_doc_link_mod_ambiguity/struct.B.html '//a/@href' '../intra_doc_link_mod_ambiguity/fn.foo.html'\n/// Function is [`fn@foo`]\npub struct B;\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test that `!` cannot be indexed\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\nfn main() {\n (return)[0u]; //~ ERROR cannot index a value of type `!`\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for `Ipv4Addr` methods in a const context\n"
},
{
"from": "gpt",
"value": "// run-pass\n\n#![feature(ip)]\n#![feature(const_ipv4)]\n\nuse std::net::Ipv4Addr;\n\nfn main() {\n const IP_ADDRESS: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);\n assert_eq!(IP_ADDRESS, Ipv4Addr::LOCALHOST);\n\n const OCTETS: [u8; 4] = IP_ADDRESS.octets();\n assert_eq!(OCTETS, [127, 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_PRIVATE : bool = IP_ADDRESS.is_private();\n assert!(!IS_PRIVATE);\n\n const IS_LINK_LOCAL : bool = IP_ADDRESS.is_link_local();\n assert!(!IS_LINK_LOCAL);\n\n const IS_SHARED : bool = IP_ADDRESS.is_shared();\n assert!(!IS_SHARED);\n\n const IS_IETF_PROTOCOL_ASSIGNMENT : bool = IP_ADDRESS.is_ietf_protocol_assignment();\n assert!(!IS_IETF_PROTOCOL_ASSIGNMENT);\n\n const IS_BENCHMARKING : bool = IP_ADDRESS.is_benchmarking();\n assert!(!IS_BENCHMARKING);\n\n const IS_MULTICAST : bool = IP_ADDRESS.is_multicast();\n assert!(!IS_MULTICAST);\n\n const IS_DOCUMENTATION : bool = IP_ADDRESS.is_documentation();\n assert!(!IS_DOCUMENTATION);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test that bounds checks are elided when slice len is checked up-front\n"
},
{
"from": "gpt",
"value": "// no-system-llvm\n// compile-flags: -O\n#![crate_type = \"lib\"]\n\n// CHECK-LABEL: @already_sliced_no_bounds_check\n#[no_mangle]\npub fn already_sliced_no_bounds_check(a: &[u8], b: &[u8], c: &mut [u8]) {\n // CHECK: slice_index_len_fail\n // CHECK-NOT: panic_bounds_check\n let _ = (&a[..2048], &b[..2048], &mut c[..2048]);\n for i in 0..1024 {\n c[i] = a[i] ^ b[i];\n }\n}\n\n// make sure we're checking for the right thing: there can be a panic if the slice is too small\n// CHECK-LABEL: @already_sliced_bounds_check\n#[no_mangle]\npub fn already_sliced_bounds_check(a: &[u8], b: &[u8], c: &mut [u8]) {\n // CHECK: slice_index_len_fail\n // CHECK: panic_bounds_check\n let _ = (&a[..1023], &b[..2048], &mut c[..2048]);\n for i in 0..1024 {\n c[i] = a[i] ^ b[i];\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test to check for debug logging disabled at compile time\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\n// xfail-fast\n// compile-flags:--cfg ndebug\n// exec-env:RUST_LOG=logging-enabled-debug=debug\n\nuse std::logging;\n\nfn main() {\n if log_enabled!(logging::DEBUG) {\n fail!(\"what?! debugging?\");\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add expression tests from rcc codebase\n"
},
{
"from": "gpt",
"value": "use std::fmt::Display;\nuse thiserror::Error;\n\n// Some of the elaborate cases from the rcc codebase, which is a C compiler in\n// Rust. https://github.com/jyn514/rcc/blob/0.8.0/src/data/error.rs\n#[derive(Error, Debug)]\npub enum Error {\n #[error(\"cannot shift {} by {maximum} or more bits (got {current})\", if *.is_left { \"left\" } else { \"right\" })]\n TooManyShiftBits {\n is_left: bool,\n maximum: u64,\n current: u64,\n },\n\n #[error(\"#error {}\", (.0).iter().copied().collect::<Vec<_>>().join(\" \"))]\n User(Vec<&'static str>),\n\n #[error(\"overflow while parsing {}integer literal\",\n if let Some(signed) = .is_signed {\n if *signed { \"signed \"} else { \"unsigned \"}\n } else {\n \"\"\n }\n )]\n IntegerOverflow { is_signed: Option<bool> },\n\n #[error(\"overflow while parsing {}integer literal\", match .is_signed {\n Some(true) => \"signed \",\n Some(false) => \"unsigned \",\n None => \"\",\n })]\n IntegerOverflow2 { is_signed: Option<bool> },\n}\n\nfn assert<T: Display>(expected: &str, value: T) {\n assert_eq!(expected, value.to_string());\n}\n\n#[test]\nfn test_rcc() {\n assert(\n \"cannot shift left by 32 or more bits (got 50)\",\n Error::TooManyShiftBits {\n is_left: true,\n maximum: 32,\n current: 50,\n },\n );\n\n assert(\"#error A B C\", Error::User(vec![\"A\", \"B\", \"C\"]));\n\n assert(\n \"overflow while parsing signed integer literal\",\n Error::IntegerOverflow {\n is_signed: Some(true),\n },\n );\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add tests for hidden types\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#![crate_name = \"foo\"]\n\n#[doc(hidden)]\npub trait Foo {}\n\ntrait Dark {}\n\npub trait Bam {}\n\npub struct Bar;\n\nstruct Hidden;\n\n// @!has foo/struct.Bar.html '//*[@id=\"impl-Foo\"]' 'impl Foo for Bar'\nimpl Foo for Bar {}\n// @!has foo/struct.Bar.html '//*[@id=\"impl-Dark\"]' 'impl Dark for Bar'\nimpl Dark for Bar {}\n// @has foo/struct.Bar.html '//*[@id=\"impl-Bam\"]' 'impl Bam for Bar'\n// @has foo/trait.Bam.html '//*[@id=\"implementors-list\"]' 'impl Bam for Bar'\nimpl Bam for Bar {}\n// @!has foo/trait.Bam.html '//*[@id=\"implementors-list\"]' 'impl Bam for Hidden'\nimpl Bam for Hidden {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test that lambdas can't deinitialize upvars\n"
},
{
"from": "gpt",
"value": "// error-pattern:assigning to upvar\nfn force(f: &block() -> int) -> int { ret f(); }\nfn main() {\n let x = 5;\n let f = lambda () -> int { let y = 6; x <- y; ret 7 };\n assert (force(f) == 7);\n log x;\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for the returned balances from Kraken\n"
},
{
"from": "gpt",
"value": "#[cfg(test)]\r\nmod kraken_tests {\r\n extern crate coinnect;\r\n\r\n use self::coinnect::kraken::KrakenApi;\r\n\r\n /// IMPORTANT: Real keys are needed in order to retrieve the balance\r\n #[test]\r\n fn balance_should_return_a_result() {\r\n use std::path::PathBuf;\r\n let path = PathBuf::from(\"./keys_real.json\");\r\n let mut api = KrakenApi::new_from_file(\"account_kraken\", path);\r\n let result = api.get_account_balance();\r\n\r\n assert!(result.unwrap().contains_key(\"result\"));\r\n }\r\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add simple UtpStream test using only the public API.\n"
},
{
"from": "gpt",
"value": "#![feature(macro_rules)]\n\nextern crate utp;\n\nuse std::io::test::next_test_ip4;\nuse utp::UtpStream;\n\nmacro_rules! iotry(\n ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!(\"{}\", e) })\n)\n\n\n#[test]\nfn test_stream_open_and_close() {\n let server_addr = next_test_ip4();\n let mut server = iotry!(UtpStream::bind(server_addr));\n\n spawn(proc() {\n let mut client = iotry!(UtpStream::connect(server_addr));\n iotry!(client.close());\n drop(client);\n });\n\n iotry!(server.read_to_end());\n iotry!(server.close());\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "WIP: Implement tests for syscalls in example scheme\n"
},
{
"from": "human",
"value": "use std::fs::File;\nuse std::io::{Read, Write};\n\nuse system::scheme::{Packet, Scheme};\n\nextern crate system;\n\nstruct ExampleScheme;\n\nimpl Scheme for ExampleScheme {\n\n}\n\nfn main() {\n //In order to handle example:, we create :example\n let mut scheme = File::create(\":example\").unwrap();\n loop {\n let mut packet = Packet::default();\n if scheme.read(&mut packet).unwrap() == 0 {\n panic!(\"Unexpected EOF\");\n }\n\n println!(\"Received: {:?}\", packet);\n\n packet.a = 0;\n scheme.write(&packet).unwrap();\n }\n}\n"
},
{
"from": "gpt",
"value": "use std::fs::File;\nuse std::io::{Read, Write};\n\nuse system::error::{Error, Result, ENOENT, EBADF};\nuse system::scheme::{Packet, Scheme};\n\nextern crate system;\n\nstruct ExampleScheme;\n\nimpl Scheme for ExampleScheme {\n fn open(&mut self, path: &str, flags: usize, mode: usize) -> Result {\n println!(\"open {:X} = {}, {:X}, {:X}\", path.as_ptr() as usize, path, flags, mode);\n Ok(0)\n }\n\n #[allow(unused_variables)]\n fn unlink(&mut self, path: &str) -> Result {\n println!(\"unlink {}\", path);\n Err(Error::new(ENOENT))\n }\n\n #[allow(unused_variables)]\n fn mkdir(&mut self, path: &str, mode: usize) -> Result {\n println!(\"mkdir {}, {:X}\", path, mode);\n Err(Error::new(ENOENT))\n }\n\n /* Resource operations */\n\n #[allow(unused_variables)]\n fn read(&mut self, id: usize, buf: &mut [u8]) -> Result {\n println!(\"read {}, {:X}, {}\", id, buf.as_mut_ptr() as usize, buf.len());\n Err(Error::new(EBADF))\n }\n\n #[allow(unused_variables)]\n fn write(&mut self, id: usize, buf: &[u8]) -> Result {\n println!(\"write {}, {:X}, {}\", id, buf.as_ptr() as usize, buf.len());\n Err(Error::new(EBADF))\n }\n\n #[allow(unused_variables)]\n fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result {\n println!(\"seek {}, {}, {}\", id, pos, whence);\n Err(Error::new(EBADF))\n }\n\n #[allow(unused_variables)]\n fn sync(&mut self, id: usize) -> Result {\n println!(\"sync {}\", id);\n Err(Error::new(EBADF))\n }\n\n #[allow(unused_variables)]\n fn truncate(&mut self, id: usize, len: usize) -> Result {\n println!(\"truncate {}, {}\", id, len);\n Err(Error::new(EBADF))\n }\n}\n\nfn main() {\n //In order to handle example:, we create :example\n let mut scheme = ExampleScheme;\n let mut socket = File::create(\":example\").unwrap();\n loop {\n let mut packet = Packet::default();\n if socket.read(&mut packet).unwrap() == 0 {\n panic!(\"Unexpected EOF\");\n }\n println!(\"Recv {:?}\", packet);\n\n scheme.handle(&mut packet);\n\n socket.write(&packet).unwrap();\n println!(\"Sent {:?}\", packet);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for Item::Verbatim splitting a None group\n\n(see issue #1235)\n"
},
{
"from": "gpt",
"value": "use proc_macro2::{Delimiter, Group};\nuse quote::quote;\n\n#[test]\nfn main() {\n // Okay. Rustc allows top-level `static` with no value syntactically, but\n // not semantically. Syn parses as Item::Verbatim.\n let tokens = quote!(\n pub static FOO: usize;\n pub static BAR: usize;\n );\n let file = syn::parse2::<syn::File>(tokens).unwrap();\n println!(\"{:#?}\", file);\n\n // Okay.\n let inner = Group::new(\n Delimiter::None,\n quote!(static FOO: usize = 0; pub static BAR: usize = 0),\n );\n let tokens = quote!(pub #inner;);\n let file = syn::parse2::<syn::File>(tokens).unwrap();\n println!(\"{:#?}\", file);\n\n // Parser crash.\n let inner = Group::new(\n Delimiter::None,\n quote!(static FOO: usize; pub static BAR: usize),\n );\n let tokens = quote!(pub #inner;);\n let file = syn::parse2::<syn::File>(tokens).unwrap();\n println!(\"{:#?}\", file);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for uninit raw ptrs\n"
},
{
"from": "gpt",
"value": "fn main() {\n let _val = unsafe { std::mem::MaybeUninit::<*const u8>::uninit().assume_init() };\n //~^ ERROR type validation failed at .value: encountered uninitialized raw pointer\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for mocking Generic Associated Types\n\nNo code changes are necessary to get this test working.\n"
},
{
"from": "gpt",
"value": "#! vim: tw=80\n//! automock a trait with Generic Associated Types\n#![cfg_attr(feature = \"nightly\", feature(generic_associated_types))]\n#![deny(warnings)]\n\nuse cfg_if::cfg_if;\n\ncfg_if! {\n if #[cfg(feature = \"nightly\")] {\n use mockall::*;\n\n // The lifetime must have the same name as in the next() method.\n #[automock(type Item=&'a u32;)]\n trait LendingIterator {\n type Item<'a> where Self: 'a;\n\n // Clippy doesn't know that Mockall will need the liftime when it\n // expands the macro.\n #[allow(clippy::needless_lifetimes)]\n fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;\n }\n\n // It isn't possible to safely set an expectation for a non-'static\n // return value (because the mock object doesn't have any lifetime\n // parameters itself), but unsafely setting such an expectation is a\n // common use case.\n #[test]\n fn return_const() {\n let mut mock = MockLendingIterator::new();\n let x = 42u32;\n let xstatic: &'static u32 = unsafe{ std::mem::transmute(&x) };\n mock.expect_next().return_const(Some(xstatic));\n assert_eq!(42u32, *mock.next().unwrap());\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add another test using projection types in impls.\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 where the impl self type uses a projection from a constant type.\n\ntrait Int\n{\n type T;\n}\n\ntrait NonZero\n{\n fn non_zero(self) -> bool;\n}\n\nimpl Int for i32 { type T = i32; }\nimpl Int for i64 { type T = i64; }\nimpl Int for u32 { type T = u32; }\nimpl Int for u64 { type T = u64; }\n\nimpl NonZero for <i32 as Int>::T { fn non_zero(self) -> bool { self != 0 } }\nimpl NonZero for <i64 as Int>::T { fn non_zero(self) -> bool { self != 0 } }\nimpl NonZero for <u32 as Int>::T { fn non_zero(self) -> bool { self != 0 } }\nimpl NonZero for <u64 as Int>::T { fn non_zero(self) -> bool { self != 0 } }\n\nfn main ()\n{\n assert!(NonZero::non_zero(22_i32));\n assert!(NonZero::non_zero(22_i64));\n assert!(NonZero::non_zero(22_u32));\n assert!(NonZero::non_zero(22_u64));\n\n assert!(!NonZero::non_zero(0_i32));\n assert!(!NonZero::non_zero(0_i64));\n assert!(!NonZero::non_zero(0_u32));\n assert!(!NonZero::non_zero(0_u64));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a new test case to verify behavior.\n"
},
{
"from": "gpt",
"value": "// run-pass\n#![feature(trait_upcasting)]\n#![allow(incomplete_features)]\n\ntrait Foo<T: Default + ToString>: Bar<i32> + Bar<T> {}\ntrait Bar<T: Default + ToString> {\n fn bar(&self) -> String {\n T::default().to_string()\n }\n}\n\nstruct S1;\n\nimpl Bar<i32> for S1 {}\nimpl Foo<i32> for S1 {}\n\nstruct S2;\nimpl Bar<i32> for S2 {}\nimpl Bar<bool> for S2 {}\nimpl Foo<bool> for S2 {}\n\nfn test1(x: &dyn Foo<i32>) {\n let s = x as &dyn Bar<i32>;\n assert_eq!(\"0\", &s.bar().to_string());\n}\n\nfn test2(x: &dyn Foo<bool>) {\n let p = x as &dyn Bar<i32>;\n assert_eq!(\"0\", &p.bar().to_string());\n let q = x as &dyn Bar<bool>;\n assert_eq!(\"false\", &q.bar().to_string());\n}\n\nfn main() {\n let s1 = S1;\n test1(&s1);\n let s2 = S2;\n test2(&s2);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test for struct-like variants in consts\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 E {\n S0 { s: ~str },\n S1 { u: uint }\n}\n\nconst C: E = S1 { u: 23 };\n\nfn main() {\n match C {\n S0 { _ } => fail!(),\n S1 { u } => assert u == 23\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add run-pass test for reinitialized unions.\n\nThis commit adds a run-pass test for the subset of\n`src/test/ui/borrowck/borrowck-union-move-assign.rs` that is intended to\npass as the union is reinitialized.\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-pass\n\n#![feature(untagged_unions)]\n\nstruct A;\nstruct B;\n\nunion U {\n a: A,\n b: B,\n}\n\nfn main() {\n unsafe {\n {\n let mut u = U { a: A };\n let a = u.a;\n u.a = A;\n let a = u.a; // OK\n }\n {\n let mut u = U { a: A };\n let a = u.a;\n u.b = B;\n let a = u.a; // OK\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for derive(PartialOrd) correctness\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// Original issue: #49650\n\n#[derive(PartialOrd, PartialEq)]\nstruct FloatWrapper(f64);\n\nfn main() {\n assert!((0.0 / 0.0 >= 0.0) == (FloatWrapper(0.0 / 0.0) >= FloatWrapper(0.0)))\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test that autoref'ing beyond method receivers does not leak into two-phase borrows.\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: lxl nll g2p\n//[lxl]compile-flags: -Z borrowck=mir -Z two-phase-borrows\n//[nll]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z nll\n//[g2p]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z nll -Z two-phase-beyond-autoref\n\n#![feature(rustc_attrs)]\n\n// This is a test checking that when we limit two-phase borrows to\n// method receivers, we do not let other kinds of auto-ref to leak\n// through.\n//\n// The g2p revision illustrates the \"undesirable\" behavior you would\n// otherwise observe without limiting the phasing to autoref on method\n// receivers (namely, that the test would pass).\n\nfn bar(x: &mut u32) {\n foo(x, *x);\n //[lxl]~^ ERROR cannot use `*x` because it was mutably borrowed [E0503]\n //[nll]~^^ ERROR cannot use `*x` because it was mutably borrowed [E0503]\n}\n\nfn foo(x: &mut u32, y: u32) {\n *x += y;\n}\n\n#[rustc_error]\nfn main() { //[g2p]~ ERROR compilation successful\n bar(&mut 5);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a utility for printing out a table of bytes\n"
},
{
"from": "gpt",
"value": "pub fn print_byte_table<'a, T: Iterator<&'a u8>>(iter: T) {\n print!(\" \");\n for x in range::<u8>(0, 16) {\n print!(\" {:02x}\", x);\n\n if x == 15 {\n print!(\"\\n\");\n }\n }\n\n for (i, value) in iter.enumerate() {\n if i % 16 == 0 {\n if i > 0 {\n println!(\"\");\n }\n print!(\"{:04x}\", i);\n }\n print!(\" {:02x}\", *value);\n }\n\n println!(\"\\n\");\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a struct representing the chosen device and interface options\n"
},
{
"from": "gpt",
"value": "use std::fmt;\n\n\nstatic DEFAULTDEVICE: &'static str = \"/dev/net/tun\";\nstatic DEFAULTINTERFACE: &'static str = \"tap0\";\n\n\npub enum CloneDevice {\n DefaultDevice,\n UserDefinedDevice(String)\n}\n\n\nimpl fmt::Show for CloneDevice {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match *self {\n DefaultDevice => write!(f, \"{}\", DEFAULTDEVICE),\n UserDefinedDevice(ref d) => write!(f, \"{}\", d),\n }\n }\n}\n\n\npub enum InterfaceName {\n DefaultInterface,\n UserDefinedName(String)\n}\n\n\nimpl fmt::Show for InterfaceName {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match *self {\n DefaultInterface => write!(f, \"{}\", DEFAULTINTERFACE),\n UserDefinedName(ref i) => write!(f, \"{}\", i),\n }\n }\n}\n\n\npub struct DeviceInfo {\n clone_device: CloneDevice,\n interface: InterfaceName\n}\n\n\nimpl DeviceInfo {\n pub fn new(d: CloneDevice, i: InterfaceName) -> DeviceInfo {\n DeviceInfo {clone_device: d, interface: i}\n }\n\n\n pub fn get_clone_device_name(&self) -> String {\n format!(\"{}\", self.clone_device)\n }\n\n\n pub fn get_interface_name(&self) -> String {\n format!(\"{}\", self.interface)\n }\n}\n\n\nimpl fmt::Show for DeviceInfo {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"clone device: {}, interface name: {}\", self.clone_device, self.interface)\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add new test case showing that supertraits are not enough\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 that when a `..` impl applies, we also check that any\n// supertrait conditions are met.\n\n#![feature(optin_builtin_traits)]\n\ntrait NotImplemented { }\n\ntrait MyTrait\n where Option<Self> : NotImplemented\n{}\n\nimpl NotImplemented for i32 {}\n\nimpl MyTrait for .. {}\n\nfn foo<T:MyTrait>() {\n bar::<Option<T>>()\n //~^ ERROR not implemented for the type `Option<T>`\n //\n // This should probably typecheck. This is #20671.\n}\n\nfn bar<T:NotImplemented>() { }\n\nfn main() {\n foo::<i32>(); //~ ERROR not implemented for the type `i32`\n bar::<Option<i32>>(); //~ ERROR not implemented for the type `Option<i32>`\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add hello world server example\n"
},
{
"from": "gpt",
"value": "extern crate clap;\nextern crate fibers;\nextern crate futures;\nextern crate miasht;\n\nuse fibers::{Executor, ThreadPoolExecutor};\nuse futures::{Future, BoxFuture};\nuse miasht::{Server, Status};\nuse miasht::builtin::servers::{SimpleHttpServer, RawConnection};\nuse miasht::builtin::headers::ContentLength;\nuse miasht::builtin::FutureExt;\n\nfn main() {\n let mut executor = ThreadPoolExecutor::new().unwrap();\n let addr = \"0.0.0.0:3000\".parse().unwrap();\n let server = SimpleHttpServer::new((), echo);\n let server = server.start(addr, executor.handle());\n let monitor = executor.spawn_monitor(server.join());\n let result = executor.run_fiber(monitor).unwrap();\n println!(\"HTTP Server shutdown: {:?}\", result);\n}\n\nfn echo(_: (), connection: RawConnection) -> BoxFuture<(), ()> {\n connection.read_request()\n .and_then(|request| {\n let bytes = b\"Hello, World\";\n let connection = request.finish();\n let mut response = connection.build_response(Status::Ok);\n response.add_header(&ContentLength(bytes.len() as u64));\n response.finish().write_all_bytes(bytes).then(|_| Ok(()))\n })\n .map_err(|e| {\n println!(\"Error: {:?}\", e);\n ()\n })\n .boxed()\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Implement hashing for trie metadata.\n"
},
{
"from": "gpt",
"value": "use std::fmt::Debug;\nuse std::hash::{Hash, Hasher, SipHasher};\n\n#[derive(Debug,PartialEq,Eq,Clone)]\npub enum IFreq {\n Never,\n Depth(u64, u64),\n First(u64),\n Const(u64),\n}\n\nimpl Hash for IFreq {\n fn hash<H: Hasher>(&self, state: &mut H) {\n match *self {\n IFreq::Never => {\n \"Adapton.Trie.Meta.Freq#Never\".hash(state);\n },\n IFreq::Depth(i, j) => {\n \"Adapton.Trie.Meta.Freq#Depth\".hash(state);\n i.hash(state);\n j.hash(state);\n },\n IFreq::First(n) => {\n \"Adapton.Trie.Meta.Freq#First\".hash(state);\n n.hash(state);\n },\n IFreq::Const(i) => {\n \"Adapton.Trie.Meta.Freq#Const\".hash(state);\n i.hash(state);\n },\n }\n }\n}\n\n#[derive(Debug,PartialEq,Eq,Hash,Clone)]\npub struct Meta {\n min_depth: u64,\n ifreq: IFreq,\n}\n\npub trait MetaT {\n fn hash_seeded(&self, u64);\n}\n\nimpl MetaT for Meta {\n fn hash_seeded(&self, seed:u64) {\n let mut hasher = SipHasher::new_with_keys(0, seed);\n \"Adapton.Trie.Meta\".hash(&mut hasher);\n self.min_depth.hash(&mut hasher);\n self.ifreq.hash(&mut hasher);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add example showing incorrect handling of gamma\n"
},
{
"from": "gpt",
"value": "//! Demonstrates the current incorrect handling of gamma for RGB images\n\nextern crate image;\nextern crate imageproc;\n\nuse image::{ImageBuffer, Rgb};\nuse imageproc::pixelops::interpolate;\n\nfn main() {\n let red = Rgb([255, 0, 0]);\n let green = Rgb([0, 255, 0]);\n\n // We'll create an 800 pixel wide gradient image.\n let left_weight = |x| x as f32 / 800.0;\n\n let naive_blend = |x| {\n interpolate(red, green, left_weight(x))\n };\n\n let mut naive_image = ImageBuffer::new(800, 400);\n for y in 0..naive_image.height() {\n for x in 0..naive_image.width() {\n naive_image.put_pixel(x, y, naive_blend(x));\n }\n }\n naive_image.save(\"naive_blend.png\").unwrap();\n\n let gamma = 2.2f32;\n let gamma_inv = 1.0 / gamma;\n\n let gamma_blend_channel = |l, r, w| {\n let l = (l as f32).powf(gamma);\n let r = (r as f32).powf(gamma);\n let s: f32 = l * w + r * (1.0 - w);\n s.powf(gamma_inv) as u8\n };\n\n let gamma_blend = |x| {\n let w = left_weight(x);\n Rgb([\n gamma_blend_channel(red[0], green[0], w),\n gamma_blend_channel(red[1], green[1], w),\n gamma_blend_channel(red[2], green[2], w)\n ])\n };\n\n let mut gamma_image = ImageBuffer::new(800, 400);\n for y in 0..gamma_image.height() {\n for x in 0..gamma_image.width() {\n gamma_image.put_pixel(x, y, gamma_blend(x));\n }\n }\n gamma_image.save(\"gamma_blend.png\").unwrap();\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add example that periodically shows the current clock ticks.\n"
},
{
"from": "gpt",
"value": "#![no_std]\n/**\n * This example shows a repeated timer combined with reading and displaying the current time in\n * clock ticks.\n **/\nuse core::fmt::Write;\nuse libtock::console::Console;\nuse libtock::result::TockResult;\nuse libtock::timer;\nuse libtock::timer::Duration;\n\n#[libtock::main]\nasync fn main() -> TockResult<()> {\n let mut console = Console::new();\n const DELAY_MS: isize = 50;\n\n for i in 0.. {\n let mut timer_with_callback = timer::with_callback(|_, _| {});\n let timer = timer_with_callback.init()?;\n let ticks = timer.get_current_clock()?.num_ticks();\n writeln!(\n console,\n \"[{}] Waited {} ms. Now is {:#010x} ticks\",\n i,\n i * DELAY_MS,\n ticks\n )?;\n timer::sleep(Duration::from_ms(DELAY_MS)).await?;\n }\n\n Ok(())\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add simple `[repr(align)]` codegen test.\n\nChecks alloca and memcpy are aligned correctly.\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#![crate_type = \"lib\"]\n\n#![feature(attr_literals)]\n#![feature(repr_align)]\n\n#[repr(align(64))]\npub struct Align64(i32);\n\npub struct Nested64 {\n a: Align64,\n b: i32,\n c: i32,\n d: i8,\n}\n\npub enum Enum64 {\n A(Align64),\n B(i32),\n}\n\n// CHECK-LABEL: @align64\n#[no_mangle]\npub fn align64(i : i32) -> Align64 {\n// CHECK: %a64 = alloca %Align64, align 64\n// CHECK: call void @llvm.memcpy.{{.*}}(i8* %{{.*}}, i8* %{{.*}}, i{{[0-9]+}} 64, i32 64, i1 false)\n let a64 = Align64(i);\n a64\n}\n\n// CHECK-LABEL: @nested64\n#[no_mangle]\npub fn nested64(a: Align64, b: i32, c: i32, d: i8) -> Nested64 {\n// CHECK: %n64 = alloca %Nested64, align 64\n// CHECK: %a = alloca %Align64, align 64\n let n64 = Nested64 { a, b, c, d };\n n64\n}\n\n// CHECK-LABEL: @enum64\n#[no_mangle]\npub fn enum64(a: Align64) -> Enum64 {\n// CHECK: %e64 = alloca %Enum64, align 64\n// CHECK: %a = alloca %Align64, align 64\n let e64 = Enum64::A(a);\n e64\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add a simple region test, xfail'd in the pretty printer\n"
},
{
"from": "gpt",
"value": "// xfail-pretty\n\nfn main() {\n unsafe {\n let x : int = 3;\n let y : &mut int = &mut x;\n *y = 5;\n log(debug, *y);\n }\n}\n\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an example program which demonstates detailed detection\n"
},
{
"from": "gpt",
"value": "extern crate cld2;\n\nuse std::default::Default;\nuse cld2::{detect_language_ext, Format};\n\nstatic TEXTS: &'static [&'static str] = &[\n // English.\n // From Coleridge's \"The Rime of the Ancient Mariner\".\n \"It is an ancient Mariner,\nAnd he stoppeth one of three.\n'By thy long grey beard and glittering eye,\nNow wherefore stopp'st thou me?\",\n\n // French.\n // Traditional children's song.\n \"Sur le pont d'Avignon,\nL'on y danse, l'on y danse,\nSur le pont d'Avignon\nL'on y danse tous en rond.\nLes belles dames font comme ça\nEt puis encore comme ça.\nLes messieurs font comme ça\nEt puis encore comme ça.\",\n\n // Mixed French and English.\n // Combination of the two above.\n \"It is an ancient Mariner,\nAnd he stoppeth one of three.\n'By thy long grey beard and glittering eye,\nNow wherefore stopp'st thou me?\n\nSur le pont d'Avignon,\nL'on y danse, l'on y danse,\nSur le pont d'Avignon\nL'on y danse tous en rond.\nLes belles dames font comme ça\nEt puis encore comme ça.\nLes messieurs font comme ça\nEt puis encore comme ça.\",\n\n // Middle Egyptian.\n // (\"rA n(y) pr(i).t m hrw\" or \"The Book of Going Forth by Day\")\n //\n // This is intended to test Unicode characters that don't fit into 16\n // bits, and to see whether cld2 can detect obscure languages using\n // nothing but script data.\n \"𓂋𓏤𓈖𓉐𓂋𓏏𓂻𓅓𓉔𓂋𓅱𓇳\",\n\n // Short text.\n \"blah\"\n];\n\nfn main() {\n for (i, &text) in TEXTS.iter().enumerate() {\n println!(\"=== Text #{}\\n\", i + 1);\n\n let detected =\n detect_language_ext(text, Format::Text, &Default::default());\n\n println!(\"Language: {}\", detected.language);\n println!(\"Reliability: {}\", detected.reliability);\n println!(\"Bytes of text: {}\", detected.text_bytes);\n println!(\"\\n= Per-language scores:\\n\");\n\n for score in detected.scores.iter() {\n println!(\"Language: {}\", score.language);\n println!(\"Percent of input: {}%\", score.percent);\n println!(\"Norm: {}\\n\", score.normalized_score);\n }\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an example of using the typed API\n"
},
{
"from": "gpt",
"value": "// This example assumes you have InfluxDB running at http://localhost:8086/\n// without authentication and that there is an existing database named\n// `my_database`.\n\nextern crate tokio_core;\nextern crate futures;\nextern crate influxdb;\n\n#[macro_use]\nextern crate influxdb_derive;\n\nuse influxdb::AsyncDb;\n\nconst HTTP_BASE_URL: &'static str = \"http://localhost:8086/\";\n\n#[derive(Measurement)]\n#[influx(rename = \"my_measure\")]\nstruct MyMeasure {\n #[influx(tag)]\n region: String,\n #[influx(field)]\n count: i32,\n}\n\nfn main() {\n let mut core = tokio_core::reactor::Core::new()\n .expect(\"Unable to create reactor core\");\n\n // The name of the database in InfluxDB\n let db_name = \"my_database\";\n\n // Create an influxdb::AsyncDb instance pointing to your InfluxDB\n // instance.\n let async_db = AsyncDb::new(core.handle(), HTTP_BASE_URL, db_name)\n .expect(\"Unable to create AsyncDb\");\n\n // influxdb supports batched insertion of multiple records in one request.\n let batch = vec![\n MyMeasure { region: String::from(\"us-east\"), count: 3 },\n MyMeasure { region: String::from(\"us-west\"), count: 20 },\n MyMeasure { region: String::from(\"us-north\"), count: 45 },\n ];\n\n let insert = async_db.add_data(&batch);\n\n core.run(insert).expect(\"Unable to run future to completion\");\n\n let query = async_db.query(r#\"SELECT \"count\" FROM \"my_measure\"\"#);\n\n let response = core.run(query).expect(\"Unable to run future to completion\");\n\n println!(\"Values: {:#?}\", response.results[0].series[0]);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add testing coverage for assigning to immutable thread-locals.\n\nIt is currently allowed to perform such assignments when not making use\nof NLL. NLL already does this right, but let's add a test in place to\nensure it never regresses.\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\n// Regression test for issue #47053\n\n#![feature(nll)]\n#![feature(thread_local)]\n\n#[thread_local]\nstatic FOO: isize = 5;\n\nfn main() {\n FOO = 6; //~ ERROR cannot assign to immutable item `FOO` [E0594]\n}\n"
}
] | rust | chosen |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.