conversations listlengths 2 3 | source stringclasses 1 value | stack stringclasses 1 value |
|---|---|---|
[
{
"from": "human",
"value": "testsuite: Test that init and forget are both unsafe\n"
},
{
"from": "gpt",
"value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse core::unstable::intrinsics::{init, forget};\n\n// Test that the `forget` and `init` intrinsics are really unsafe\npub fn main() {\n let stuff = init::<int>(); //~ ERROR access to unsafe function requires unsafe\n forget(stuff); //~ ERROR access to unsafe function requires unsafe\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add test for LHS expression check\n"
},
{
"from": "gpt",
"value": "// Copyright 2012-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\nfn main() {\n 1 = 2; //~ ERROR illegal left-hand side expression\n 1 += 2; //~ ERROR illegal left-hand side expression\n (1, 2) = (3, 4); //~ ERROR illegal left-hand side expression\n\n let (a, b) = (1, 2);\n (a, b) = (3, 4); //~ ERROR illegal left-hand side expression\n\n None = Some(3); //~ ERROR illegal left-hand side expression\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rather slow solution to problem 25\n"
},
{
"from": "gpt",
"value": "#[macro_use] extern crate libeuler;\nextern crate num;\n\nuse num::traits::Zero;\nuse num::traits::One;\nuse num::bigint::BigUint;\nuse std::mem::replace;\n\n/// The Fibonacci sequence is defined by the recurrence relation:\n///\n/// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.\n///\n/// Hence the first 12 terms will be:\n///\n/// F1 = 1\n/// F2 = 1\n/// F3 = 2\n/// F4 = 3\n/// F5 = 5\n/// F6 = 8\n/// F7 = 13\n/// F8 = 21\n/// F9 = 34\n/// F10 = 55\n/// F11 = 89\n/// F12 = 144\n///\n/// The 12th term, F12, is the first term to contain three digits.\n///\n/// What is the first term in the Fibonacci sequence to contain 1000 digits?\nfn main() {\n solutions! {\n inputs: (digits: usize = 1000)\n\n sol naive {\n let min_bits = digits as f32 * 2.5f32;\n let mut current = BigUint::zero();\n let mut previous = BigUint::one();\n let mut i = 0;\n\n println!(\"Minimum bits needed to represent {} digits is {}\", digits, min_bits);\n\n loop {\n let new = current + &previous;\n current = replace(&mut previous, new);\n\n i += 1;\n\n if current.bits() as f32 >= min_bits {\n if format!(\"{}\", current).len() >= digits {\n break;\n }\n }\n }\n\n i\n }\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add a test for regions, traits, and variance.\n\nCloses #12470.\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// Issue #12470.\n\ntrait X {\n fn get_i(&self) -> int;\n}\n\nstruct B {\n i: int\n}\n\nimpl X for B {\n fn get_i(&self) -> int {\n self.i\n }\n}\n\nimpl Drop for B {\n fn drop(&mut self) {\n println!(\"drop\");\n }\n}\n\nstruct A<'r> {\n p: &'r X\n}\n\nfn make_a<'r>(p:&'r X) -> A<'r> {\n A{p:p}\n}\n\nfn make_make_a() -> A {\n let b: Box<B> = box B {\n i: 1,\n };\n let bb: &B = b; //~ ERROR `*b` does not live long enough\n make_a(bb)\n}\n\nfn main() {\n let a = make_make_a();\n println!(\"{}\", a.p.get_i());\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a simple encoding example\n"
},
{
"from": "gpt",
"value": "// Encode the same tiny blank frame 30 times\nuse rav1e::*;\n\nfn main() {\n let mut cfg = Config::default();\n\n cfg.enc.width = 64;\n cfg.enc.height = 96;\n\n cfg.enc.speed_settings = SpeedSettings::from_preset(9);\n\n let mut ctx: Context<u16> = cfg.new_context();\n\n let f = ctx.new_frame();\n\n let limit = 30;\n\n for i in 0..limit {\n println!(\"Sending frame {}\", i);\n match ctx.send_frame(f.clone()) {\n Ok(_) => {}\n Err(e) => match e {\n EncoderStatus::EnoughData => {\n println!(\"Unable to append frame {} to the internal queue\", i);\n }\n _ => {\n panic!(\"Unable to send frame {}\", i);\n }\n }\n }\n }\n\n ctx.flush();\n\n // Test that we cleanly exit once we hit the limit\n let mut i = 0;\n while i < limit + 5 {\n match ctx.receive_packet() {\n Ok(pkt) => {\n println!(\"Packet {}\", pkt.number);\n i += 1;\n }\n Err(e) => match e {\n EncoderStatus::LimitReached => {\n println!(\"Limit reached\");\n break;\n }\n EncoderStatus::Encoded => println!(\" Encoded\"),\n EncoderStatus::NeedMoreData => println!(\" Need more data\"),\n _ => {\n panic!(\"Unable to receive packet {}\", i);\n }\n }\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add solution to problem 69\n"
},
{
"from": "gpt",
"value": "#[macro_use] extern crate libeuler;\n\nuse libeuler::prime::SieveOfAtkin;\n/// Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the\n/// number of numbers less than n which are relatively prime to n. For example, as 1, 2, 4, 5, 7,\n/// and 8, are all less than nine and relatively prime to nine, φ(9)=6.\n/// n Relatively Prime φ(n) n/φ(n)\n/// 2 1 1 2\n/// 3 1,2 2 1.5\n/// 4 1,3 2 2\n/// 5 1,2,3,4 4 1.25\n/// 6 1,5 2 3\n/// 7 1,2,3,4,5,6 6 1.1666...\n/// 8 1,3,5,7 4 2\n/// 9 1,2,4,5,7,8 6 1.5\n/// 10 1,3,7,9 4 2.5\n///\n/// It can be seen that n=6 produces a maximum n/φ(n) for n ≤ 10.\n///\n/// Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.\nfn main() {\n solutions! {\n sol naive {\n let sieve = SieveOfAtkin::new(100);\n\n (0..).map(|i| {\n sieve.iter().take(i).fold(1, |v, i| v*i)\n }).take_while(|&v| v <= 1_000_000).last().unwrap()\n }\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "test: Add tests for multiple outer attributes on items\n\nIssue #487\n"
},
{
"from": "human",
"value": "// xfail-stage0\n\n#[attr = \"val\"]\nconst int x = 10;\n\n#[attr = \"val\"]\nmod mod1 {\n}\n\n#[attr = \"val\"]\nnative \"rust\" mod rustrt {\n}\n\n#[attr = \"val\"]\ntype t = obj { };\n\n#[attr = \"val\"]\nobj o() { }\n\nfn main() {\n}"
},
{
"from": "gpt",
"value": "// xfail-stage0\n\nmod test_single_attr_outer {\n\n #[attr = \"val\"]\n const int x = 10;\n\n #[attr = \"val\"]\n mod mod1 {\n }\n\n #[attr = \"val\"]\n native \"rust\" mod rustrt {\n }\n\n #[attr = \"val\"]\n type t = obj { };\n\n #[attr = \"val\"]\n obj o() { }\n\n}\n\nmod test_multi_attr_outer {\n\n #[attr1 = \"val\"]\n #[attr2 = \"val\"]\n const int x = 10;\n\n #[attr1 = \"val\"]\n #[attr2 = \"val\"]\n mod mod1 {\n }\n\n #[attr1 = \"val\"]\n #[attr2 = \"val\"]\n native \"rust\" mod rustrt {\n }\n\n #[attr1 = \"val\"]\n #[attr2 = \"val\"]\n type t = obj { };\n\n #[attr1 = \"val\"]\n #[attr2 = \"val\"]\n obj o() { }\n\n}\n\nfn main() {\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression test for old NLL ICE\n"
},
{
"from": "gpt",
"value": "// check-pass\n\n#![crate_type = \"lib\"]\n\n// In an older version, when NLL was still a feature, the following previously did not compile\n// #![feature(nll)]\n\nuse std::ops::Index;\n\npub struct Test<T> {\n a: T,\n}\n\nimpl<T> Index<usize> for Test<T> {\n type Output = T;\n\n fn index(&self, _index: usize) -> &Self::Output {\n &self.a\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a single function to get the length of a chunk, based on his index, and a few simple unit tests\n"
},
{
"from": "gpt",
"value": "use std::cmp::min;\n\nuse Byte;\n\n/// Represents a range between two Byte types\n#[derive(Debug, PartialEq)]\nstruct RangeBytes(Byte, Byte);\n\n/// Function to get the current chunk length, based on the chunk index.\nfn get_chunk_length(chunk_index: Byte,\n content_length: Byte,\n global_chunk_length: Byte)\n -> Option<RangeBytes> {\n\n // In case of wrong values, do not returns a structure\n if content_length == 0 || global_chunk_length == 0 {\n return None;\n }\n\n let b_range: Byte = chunk_index * global_chunk_length;\n\n let e_range: Byte = min(content_length,\n ((chunk_index + 1) * global_chunk_length) - 1);\n\n Some(RangeBytes(b_range, e_range))\n\n}\n\nmod test_chunk_length {\n use super::get_chunk_length;\n use super::RangeBytes;\n\n #[test]\n fn wrong_content_length_parameter_should_return_none() {\n assert_eq!(None, get_chunk_length(0, 15, 0));\n }\n\n #[test]\n fn wrong_global_chunk_length_parameter_should_return_none() {\n assert_eq!(None, get_chunk_length(0, 0, 15));\n }\n\n #[test]\n fn wrong_length_parameters_should_return_none() {\n assert_eq!(None, get_chunk_length(0, 0, 0));\n }\n\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add and xfail test for 2101\n"
},
{
"from": "gpt",
"value": "// xfail-test\nuse std;\nimport std::arena;\nimport std::arena::arena;\n\nenum hold { s(str) }\n\nfn init(ar: &a.arena::arena, str: str) -> &a.hold {\n new(*ar) s(str)\n}\n\nfn main(args: [str]) {\n let ar = arena::arena();\n let leak = init(&ar, args[0]);\n alt *leak {\n s(astr) {\n io::println(#fmt(\"%?\", astr));\n }\n };\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Create an example for node executing instructions\n"
},
{
"from": "gpt",
"value": "extern crate tis_100_superoptimizer;\n\nuse tis_100_superoptimizer::TIS_100::{Node,Instruction,Source,Destination};\n\nfn main() {\n let node: Node = Node::new();\n let last: Node = node\n .execute(Instruction::MOV(Source::Literal(1), Destination::ACC))\n .execute(Instruction::ADD(Source::ACC));\n\n println!(\"2 times 1 equals {}\", last.acc);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add support for Linux cooked-mode capture (LINKTYPE_LINUX_SLL) packets\n\nAdd support for Linux cooked-mode capture (LINKTYPE_LINUX_SLL) packets\r\n\r\nCloses #510"
},
{
"from": "gpt",
"value": "//! A Linux cooked-mode capture (LINKTYPE_LINUX_SLL) packet abstraction.\n\nuse ethernet::EtherType;\nuse pnet_macros::packet;\nuse pnet_macros_support::types::*\n\n// ref: https://wiki.wireshark.org/SLL\n// ref: https://www.tcpdump.org/linktypes/LINKTYPE_LINUX_SLL.html\n\n/// Represents an SLL packet (LINKTYPE_LINUX_SLL).\n#[packet]\npub struct SLL {\n\t#[construct_with(u16)]\n\tpub packet_type: u16be,\n\t#[construct_with(u16)]\n\tpub link_layer_address_type: u16be,\n\t#[construct_with(u16)]\n\tpub link_layer_address_len: u16be,\n\t#[construct_with(u8, u8, u8, u8, u8, u8, u8, u8)]\n\t#[length = \"8\"]\n\tpub link_layer_address: Vec<u8>,\n\t#[construct_with(u16)]\n\tpub protocol: EtherType,\n\t#[payload]\n\tpub payload: Vec<u8>,\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix Clippy and CI bug\n"
},
{
"from": "human",
"value": "//! This is the main lib.rs file for Xt Core\n\n// This file is part of Xt.\n\n// This is the Xt text editor; it edits text.\n// Copyright (C) 2016-2017 The Xt Developers\n\n// This program is free software: you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see\n// <http://www.gnu.org/licenses/>.\n\n#![cfg_attr(feature = \"ci\", feature(plugin))]\n#![cfg_attr(feature = \"ci\", plugin(clippy))]\n#![cfg_attr(feature = \"ci\", allow(unstable_features))]\n#![cfg_attr(feature = \"ci\", deny(clippy))]\n\n#![deny(missing_docs, missing_debug_implementations,\n missing_copy_implementations, trivial_casts,\n trivial_numeric_casts, unused_import_braces,\n unused_qualifications)]\n\n#[macro_use]\nextern crate slog;\nextern crate slog_json;\nextern crate slog_async;\n\n#[macro_use]\nextern crate serde_derive;\nextern crate serde_json;\n\npub mod logging;\npub mod rpc;\npub mod server;\npub mod utils;\n"
},
{
"from": "gpt",
"value": "//! This is the main lib.rs file for Xt Core\n\n// This file is part of Xt.\n\n// This is the Xt text editor; it edits text.\n// Copyright (C) 2016-2017 The Xt Developers\n\n// This program is free software: you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see\n// <http://www.gnu.org/licenses/>.\n\n#![cfg_attr(feature = \"ci\", feature(plugin))]\n#![cfg_attr(feature = \"ci\", plugin(clippy))]\n#![cfg_attr(feature = \"ci\", allow(unstable_features))]\n#![deny(missing_docs, missing_debug_implementations,\n missing_copy_implementations, trivial_casts,\n trivial_numeric_casts, unused_import_braces,\n unused_qualifications)]\n\n#[macro_use]\nextern crate slog;\nextern crate slog_json;\nextern crate slog_async;\n\n#[macro_use]\nextern crate serde_derive;\nextern crate serde_json;\n\npub mod logging;\npub mod rpc;\npub mod server;\npub mod utils;\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for the new raw writing API\n\nThis is mostly to ensure we don't break anything drastically.\n"
},
{
"from": "gpt",
"value": "//! Tests for the raw write logging functionality.\nextern crate fern;\nextern crate log;\n\nuse std::io;\nuse std::sync::Arc;\nuse std::sync::atomic::{AtomicBool, Ordering};\n\nuse log::Level::*;\n\nmod support;\n\nuse support::manual_log;\n\n#[test]\nfn test_raw_write_logging() {\n struct TestWriter {\n buf: Vec<u8>,\n flag: Arc<AtomicBool>,\n }\n\n impl io::Write for TestWriter {\n fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n self.buf.write(buf)\n }\n\n fn flush(&mut self) -> io::Result<()> {\n self.buf.flush()?;\n\n let expected = b\"[INFO] Test information message\\n\";\n\n if self.buf == expected {\n self.flag.store(true, Ordering::SeqCst);\n } else {\n eprintln!(\"{:?} does not match {:?}\", self.buf, expected);\n }\n\n Ok(())\n }\n }\n\n let flag = Arc::new(AtomicBool::new(false));\n\n // Create a basic logger configuration\n let (_max_level, logger) = fern::Dispatch::new()\n .format(|out, msg, record| out.finish(format_args!(\"[{}] {}\", record.level(), msg)))\n .level(log::LevelFilter::Info)\n .chain(io::stdout())\n .chain(Box::new(TestWriter {\n buf: Vec::new(),\n flag: flag.clone(),\n }) as Box<io::Write + Send>)\n .into_log();\n\n let l = &*logger;\n manual_log(l, Info, \"Test information message\");\n\n // ensure all File objects are dropped and OS buffers are flushed.\n log::logger().flush();\n\n assert!(\n flag.load(Ordering::SeqCst),\n \"raw Write test failed: did not match buffer\"\n );\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add tests for various ways to write 'do' and 'for' without args\n"
},
{
"from": "gpt",
"value": "// no-reformat\n// Testing various forms of `do` and `for` with empty arg lists\n\nfn f(f: fn() -> bool) {\n}\n\nfn main() {\n do f() || { true }\n do f() { true }\n do f || { true }\n do f { true }\n for f() || { }\n for f() { }\n for f || { }\n for f { }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "process: Add regression test for signal starvation\n"
},
{
"from": "gpt",
"value": "#![cfg(unix)]\n\nextern crate futures;\nextern crate tokio_process;\n\nuse futures::{Future, IntoFuture, Stream, stream};\nuse std::process::{Command, Stdio};\nuse std::sync::Arc;\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::thread;\nuse std::time::Duration;\nuse tokio_process::CommandExt;\n\nfn run_test() {\n let finished = Arc::new(AtomicBool::new(false));\n let finished_clone = finished.clone();\n\n thread::spawn(move || {\n let _ = stream::iter_ok((0..2).into_iter())\n .map(|i| Command::new(\"echo\")\n .arg(format!(\"I am spawned process #{}\", i))\n .stdin(Stdio::null())\n .stdout(Stdio::null())\n .stderr(Stdio::null())\n .spawn_async()\n .into_future()\n .flatten()\n )\n .buffered(2)\n .collect()\n .wait();\n\n finished_clone.store(true, Ordering::SeqCst);\n });\n\n thread::sleep(Duration::from_millis(100));\n assert!(finished.load(Ordering::SeqCst), \"FINISHED flag not set, maybe we deadlocked?\");\n}\n\n#[test]\nfn issue_42() {\n let max = 10;\n for i in 0..max {\n println!(\"running {}/{}\", i, max);\n run_test()\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "rustc: Add a test case for previous commit\n"
},
{
"from": "gpt",
"value": "tag opt[T] {\n none;\n}\n\nfn main() {\n auto x = none[int];\n alt (x) {\n case (none[int]) { log \"hello world\"; }\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add Breadth-First Search using The Rust Programming Language\n"
},
{
"from": "gpt",
"value": "use std::io::stdin;\nuse std::collections::VecDeque;\n\n// DFS receives a graph and the start point\nfn bfs(graph: &mut Vec<Vec<usize>>, start: usize) {\n let mut visited: Vec<bool> = Vec::new();\n visited.resize(graph.len(), false);\n\n let mut queue = VecDeque::new();\n visited[start] = true;\n queue.push_back(start);\n\n while !queue.is_empty() {\n let node = queue.pop_front().unwrap();\n println!(\"{}\", node);\n\n let adj_list = &graph[node];\n for neighbor in adj_list {\n if !visited[*neighbor] {\n visited[*neighbor] = true;\n queue.push_back(*neighbor);\n }\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 bfs(&mut graph, start);\n}\n\n#[test]\nfn test_bfs_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!(\"BFS Starting from vertex 2\");\n\n bfs(&mut graph, 2);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove ColorCast trait for now\n"
},
{
"from": "human",
"value": "use num;\n\npub trait Color: Clone + PartialEq {\n type Tag;\n type ChannelsTuple;\n\n fn num_channels() -> u32;\n fn from_tuple(values: Self::ChannelsTuple) -> Self;\n fn to_tuple(self) -> Self::ChannelsTuple;\n}\n\npub trait PolarColor: Color {\n type Angular;\n type Cartesian;\n}\n\npub trait Flatten: Color {\n type ScalarFormat;\n fn from_slice(values: &[Self::ScalarFormat]) -> Self;\n fn as_slice(&self) -> &[Self::ScalarFormat];\n}\n\npub trait HomogeneousColor: Color {\n type ChannelFormat;\n\n fn broadcast(value: Self::ChannelFormat) -> Self;\n fn clamp(self, min: Self::ChannelFormat, max: Self::ChannelFormat) -> Self;\n}\n\npub trait Color3: Color {}\npub trait Color4: Color {}\n\npub trait Lerp {\n type Position: num::Float;\n fn lerp(&self, right: &Self, pos: Self::Position) -> Self;\n}\n\npub trait Invert {\n fn invert(self) -> Self;\n}\n\npub trait Bounded {\n fn normalize(self) -> Self;\n fn is_normalized(&self) -> bool;\n}\n\npub trait ColorCast: Color {\n fn color_cast<To>(&self) -> To where To: Color<Tag = Self::Tag>;\n}\n"
},
{
"from": "gpt",
"value": "use num;\n\npub trait Color: Clone + PartialEq {\n type Tag;\n type ChannelsTuple;\n\n fn num_channels() -> u32;\n fn from_tuple(values: Self::ChannelsTuple) -> Self;\n fn to_tuple(self) -> Self::ChannelsTuple;\n}\n\npub trait PolarColor: Color {\n type Angular;\n type Cartesian;\n}\n\npub trait Flatten: Color {\n type ScalarFormat;\n fn from_slice(values: &[Self::ScalarFormat]) -> Self;\n fn as_slice(&self) -> &[Self::ScalarFormat];\n}\n\npub trait HomogeneousColor: Color {\n type ChannelFormat;\n\n fn broadcast(value: Self::ChannelFormat) -> Self;\n fn clamp(self, min: Self::ChannelFormat, max: Self::ChannelFormat) -> Self;\n}\n\npub trait Color3: Color {}\npub trait Color4: Color {}\n\npub trait Lerp {\n type Position: num::Float;\n fn lerp(&self, right: &Self, pos: Self::Position) -> Self;\n}\n\npub trait Invert {\n fn invert(self) -> Self;\n}\n\npub trait Bounded {\n fn normalize(self) -> Self;\n fn is_normalized(&self) -> bool;\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix the sentence in the comment - was to want"
},
{
"from": "human",
"value": "// Derive the `fmt::Debug` implementation for `Structure`. `Structure`\n// is a structure which contains a single `i32`.\n#[derive(Debug)]\nstruct Structure(i32);\n\n// Put a `Structure` inside of the structure `Deep`. Make it printable\n// also.\n#[derive(Debug)]\nstruct Deep(Structure);\n\nfn main() {\n // Printing with `{:?}` is similar to with `{}`.\n println!(\"{:?} months in a year.\", 12);\n println!(\"{1:?} {0:?} is the {actor:?} name.\",\n \"Slater\",\n \"Christian\",\n actor=\"actor's\");\n\n // `Structure` is printable!\n println!(\"Now {:?} will print!\", Structure(3));\n \n // The problem with `derive` is there is no control over how\n // the results look. What if I was this to just show a `7`?\n println!(\"Now {:?} will print!\", Deep(Structure(7)));\n}\n"
},
{
"from": "gpt",
"value": "// Derive the `fmt::Debug` implementation for `Structure`. `Structure`\n// is a structure which contains a single `i32`.\n#[derive(Debug)]\nstruct Structure(i32);\n\n// Put a `Structure` inside of the structure `Deep`. Make it printable\n// also.\n#[derive(Debug)]\nstruct Deep(Structure);\n\nfn main() {\n // Printing with `{:?}` is similar to with `{}`.\n println!(\"{:?} months in a year.\", 12);\n println!(\"{1:?} {0:?} is the {actor:?} name.\",\n \"Slater\",\n \"Christian\",\n actor=\"actor's\");\n\n // `Structure` is printable!\n println!(\"Now {:?} will print!\", Structure(3));\n \n // The problem with `derive` is there is no control over how\n // the results look. What if I want this to just show a `7`?\n println!(\"Now {:?} will print!\", Deep(Structure(7)));\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add floating point normalized to screen coordinate conversion\n"
},
{
"from": "human",
"value": "pub mod wireframe;\npub mod filled;\npub mod textured;\n\n/// Do perspective calculation on a point, return (x, y).\nfn perpective(x: f32, y: f32, z: f32) -> (f32, f32) {\n (x/z, y/z)\n}\n\n/// Turn floating point coordinates to something drawable on the screen, return (x, y)\nfn screen(x: f32, y: f32, screen_width: i32, screen_height: i32) -> (i32, i32) {\n ((x * (screen_height/2) as f32) as i32 + (screen_width/2),\n (y * (screen_height/2) as f32) as i32 + (screen_height/2))\n}"
},
{
"from": "gpt",
"value": "pub mod wireframe;\npub mod filled;\npub mod textured;\n\n/// Do perspective calculation on a point, return (x, y).\nfn perpective(x: f32, y: f32, z: f32) -> (f32, f32) {\n (x/z, y/z)\n}\n\n/// Turn floating point coordinates to something drawable on the screen, return (x, y)\nfn screen(x: f32, y: f32, screen_width: i32, screen_height: i32) -> (i32, i32) {\n ((x * (screen_height/2) as f32) as i32 + (screen_width/2),\n (y * (screen_height/2) as f32) as i32 + (screen_height/2))\n}\n\nfn screen_f(x: f32, y: f32, screen_width: i32, screen_height: i32) -> (f32, f32) {\n (x * (screen_height/2) as f32 + (screen_width/2) as f32,\n y * (screen_height/2) as f32 + (screen_height/2) as f32)\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add initial basic benchmark for header setters\n"
},
{
"from": "gpt",
"value": "#![feature(test)]\n\nextern crate rips_packets;\nextern crate test;\n\nuse rips_packets::ethernet::{MutEthernetPacket, ether_types};\nuse rips_packets::ipv4::{self, MutIpv4Packet};\nuse rips_packets::macaddr::MacAddr;\nuse std::net::Ipv4Addr;\nuse test::{Bencher, black_box};\n\n#[bench]\nfn set_all_ethernet_fields(b: &mut Bencher) {\n let mut buffer = [0; 14];\n let source = MacAddr([0xff, 0x00, 0xff, 0x00, 0xff, 0x00]);\n let destination = MacAddr([0x00, 0xff, 0x00, 0xff, 0x00, 0xff]);\n b.iter(|| {\n let mut packet = MutEthernetPacket::new(black_box(&mut buffer[..])).unwrap();\n packet.set_destination(black_box(destination));\n packet.set_source(black_box(source));\n packet.set_ether_type(black_box(ether_types::ARP));\n });\n}\n\n#[bench]\nfn set_all_ipv4_fields(b: &mut Bencher) {\n let mut buffer = [0; 20];\n let source = Ipv4Addr::new(192, 168, 0, 1);\n let destination = Ipv4Addr::new(192, 168, 0, 2);\n b.iter(|| {\n let mut packet = MutIpv4Packet::new(black_box(&mut buffer[..])).unwrap();\n packet.set_version(black_box(4));\n packet.set_header_length(black_box(5));\n packet.set_dscp(black_box(0));\n packet.set_ecn(black_box(0));\n packet.set_total_length(black_box(20));\n packet.set_identification(black_box(0x1337));\n packet.set_flags(black_box(0b011));\n packet.set_fragment_offset(black_box(13));\n packet.set_ttl(black_box(40));\n packet.set_protocol(black_box(ipv4::protocols::UDP));\n packet.set_header_checksum(black_box(0x1337));\n packet.set_source(black_box(source));\n packet.set_destination(black_box(destination));\n });\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for std._vec.init_elt, and an XFAILed test for std._vec.init_fn.\n"
},
{
"from": "gpt",
"value": "use std;\n\nfn test_init_elt() {\n let vec[uint] v = std._vec.init_elt[uint](uint(5), uint(3));\n check (std._vec.len[uint](v) == uint(3));\n check (v.(0) == uint(5));\n check (v.(1) == uint(5));\n check (v.(2) == uint(5));\n}\n\nfn id(uint x) -> uint {\n ret x;\n}\nfn test_init_fn() {\n let fn(uint)->uint op = id;\n let vec[uint] v = std._vec.init_fn[uint](op, uint(5));\n // FIXME #108: Can't call templated function twice in the same\n // program, at the moment.\n //check (std._vec.len[uint](v) == uint(5));\n check (v.(0) == uint(0));\n check (v.(1) == uint(1));\n check (v.(2) == uint(2));\n check (v.(3) == uint(3));\n check (v.(4) == uint(4));\n}\n\nfn main() {\n test_init_elt();\n //XFAIL: test_init_fn(); // Segfaults.\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Update i686-linux-android features to match android ABI.\n"
},
{
"from": "human",
"value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse target::Target;\n\npub fn target() -> Target {\n let mut base = super::android_base::opts();\n base.cpu = \"pentium4\".to_string();\n base.max_atomic_width = 64;\n\n Target {\n llvm_target: \"i686-linux-android\".to_string(),\n target_endian: \"little\".to_string(),\n target_pointer_width: \"32\".to_string(),\n data_layout: \"e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128\".to_string(),\n arch: \"x86\".to_string(),\n target_os: \"android\".to_string(),\n target_env: \"gnu\".to_string(),\n target_vendor: \"unknown\".to_string(),\n options: base,\n }\n}\n"
},
{
"from": "gpt",
"value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse target::Target;\n\npub fn target() -> Target {\n let mut base = super::android_base::opts();\n\n base.max_atomic_width = 64;\n\n // http://developer.android.com/ndk/guides/abis.html#x86\n base.cpu = \"pentiumpro\".to_string();\n base.features = \"+mmx,+sse,+sse2,+sse3,+ssse3\".to_string();\n\n Target {\n llvm_target: \"i686-linux-android\".to_string(),\n target_endian: \"little\".to_string(),\n target_pointer_width: \"32\".to_string(),\n data_layout: \"e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128\".to_string(),\n arch: \"x86\".to_string(),\n target_os: \"android\".to_string(),\n target_env: \"gnu\".to_string(),\n target_vendor: \"unknown\".to_string(),\n options: base,\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add tests for sw_vers parsing\n"
},
{
"from": "gpt",
"value": "extern crate regex;\n#[path=\"../src/sw_vers.rs\"]\nmod sw_vers;\n#[path=\"../src/utils.rs\"]\nmod utils;\n\nfn file() -> String {\n\"\nProductName:\tMac OS X\nProductVersion:\t10.10.5\nBuildVersion:\t14F27\n\".to_string()\n}\n\n#[test]\npub fn parses_product_name() {\n let info = sw_vers::parse(file());\n assert_eq!(info.product_name, Some(\"Mac OS X\".to_string()));\n}\n\n#[test]\npub fn parses_product_version() {\n let info = sw_vers::parse(file());\n assert_eq!(info.product_version, Some(\"10.10.5\".to_string()));\n}\n\n#[test]\npub fn parses_build_version() {\n let info = sw_vers::parse(file());\n assert_eq!(info.build_version, Some(\"14F27\".to_string()));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rust code for isbn-verifier\n\nIt passed all test cases\n"
},
{
"from": "gpt",
"value": "#![feature(ascii_ctype)]\n\npub fn is_valid_isbn(isbn: &str) -> bool {\n let mut iter = isbn.chars().peekable();\n\n if let Some(&c) = iter.peek() {\n if !c.is_ascii_digit() {\n return false;\n }\n }\n\n let mut index = 0;\n let mut sum = 0;\n let mut acc = 0;\n const X_POSTION: usize = 9;\n const MAX_LENGTH: usize = 10;\n\n while let Some(&c) = iter.peek() {\n match c {\n '-' => {\n iter.next();\n }\n _ if c.is_ascii_digit() => {\n index += 1;\n acc += c as usize - '0' as usize;\n sum += acc;\n\n iter.next();\n }\n 'X' if index == X_POSTION => {\n index += 1;\n acc += 10;\n sum += acc;\n\n iter.next();\n }\n _ => return false,\n }\n\n if index > MAX_LENGTH {\n return false;\n }\n }\n\n sum % 11 == 0\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for the osc decoder\n"
},
{
"from": "gpt",
"value": "extern crate rosc;\n\nuse rosc::{types, errors, decoder, utils};\n\n#[test]\nfn test_decode() {\n let raw_addr = \"/some/valid/address/4\";\n let addr = pad(raw_addr.as_bytes());\n // args\n let type_tags = pad(b\",\");\n let merged: Vec<u8> = addr.into_iter()\n .chain(type_tags.into_iter())\n .collect();\n let osc_packet: Result<types::OscPacket, errors::OscError> = decoder::decode(&merged);\n assert!(osc_packet.is_ok());\n match osc_packet {\n Ok(packet) => match packet {\n types::OscPacket::Message(msg) => {\n assert_eq!(raw_addr, msg.addr);\n assert!(msg.args.is_none());\n },\n _ => panic!()\n },\n Err(e) => panic!(e)\n }\n}\n\nfn pad(data: &[u8]) -> Vec<u8> {\n let pad_len: usize = utils::pad(data.len() as u64) as usize;\n let mut v: Vec<u8> = data.iter().cloned().collect();\n while v.len() < pad_len {\n v.push(0u8);\n }\n v\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rust code for say\n\nIt passed all testcases.\n"
},
{
"from": "gpt",
"value": "const TEN: u64 = 10;\nconst HUNDRED: u64 = 100;\nconst THOUSAND: u64 = 1000;\n\nfn ntable(number: u64) -> &'static str {\n match number {\n 0 => \"zero\",\n 1 => \"one\",\n 2 => \"two\",\n 3 => \"three\",\n 4 => \"four\",\n 5 => \"five\",\n 6 => \"six\",\n 7 => \"seven\",\n 8 => \"eight\",\n 9 => \"nine\",\n 10 => \"ten\",\n 11 => \"eleven\",\n 12 => \"twelve\",\n 13 => \"thirteen\",\n 14 => \"fourteen\",\n 15 => \"fifteen\",\n 16 => \"sixteen\",\n 17 => \"seventeen\",\n 18 => \"eighteen\",\n 19 => \"nineteen\",\n 20 => \"twenty\",\n 30 => \"thirty\",\n 40 => \"forty\",\n 50 => \"fifty\",\n 60 => \"sixty\",\n 70 => \"seventy\",\n 80 => \"eighty\",\n 90 => \"ninety\",\n _ => \"\",\n }\n}\n\nfn translate(number: u64) -> String {\n let mut result = String::new();\n\n let hundreds = number / HUNDRED;\n let tens = number % HUNDRED;\n\n if hundreds != 0 {\n result = ntable(hundreds).to_string() + \" hundred\";\n\n if tens == 0 {\n return result;\n } else {\n result += \" \";\n }\n }\n\n let digit = tens % TEN;\n\n if tens <= 20 || digit == 0 {\n result += ntable(tens);\n } else {\n result += ntable(tens - digit);\n result += \"-\";\n result += ntable(digit);\n }\n\n result\n}\n\nstatic UINTS: [&str; 7] = [\n \"\",\n \"thousand\",\n \"million\",\n \"billion\",\n \"trillion\",\n \"quadrillion\",\n \"quintillion\",\n];\n\npub fn encode(number: u64) -> String {\n if number < THOUSAND {\n return translate(number);\n }\n\n let mut f = number;\n let mut d = Vec::new();\n\n while f > 0 {\n let r = f % THOUSAND;\n\n d.push(r);\n\n f /= THOUSAND;\n }\n\n d.into_iter()\n .map(translate)\n .zip(UINTS.into_iter())\n .filter_map(|(v, u)| {\n if v == \"zero\" {\n return None;\n }\n\n if u.is_empty() {\n Some(v)\n } else {\n Some(v + \" \" + u)\n }\n })\n .rev()\n .collect::<Vec<_>>()\n .join(\" \")\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix ops example according to latest nightly"
},
{
"from": "human",
"value": "struct Foo;\nstruct Bar;\n\n#[deriving(Show)]\nstruct FooBar;\n\n#[deriving(Show)]\nstruct BarFoo;\n\n// The `Add<T, U>` trait needs two generic parameters:\n// * T is the type of the RHS summand, and\n// * U is the type of the sum\n// This block implements the operation: Foo + Bar = FooBar\nimpl Add<Bar, FooBar> for Foo {\n fn add(self, _rhs: Bar) -> FooBar {\n println!(\"> Foo.add(&Bar) was called\");\n\n FooBar\n }\n}\n\n// Addition can be implemented in a non-commutative way\n// This block implements the operation: Bar + Foo = BarFoo\nimpl Add<Foo, BarFoo> for Bar {\n fn add(self, _rhs: Foo) -> BarFoo {\n println!(\"> Bar.add(&Foo) was called\");\n\n BarFoo\n }\n}\n\nfn main() {\n println!(\"Foo + Bar = {}\", Foo + Bar);\n println!(\"Bar + Foo = {}\", Bar + Foo);\n}\n"
},
{
"from": "gpt",
"value": "use std::ops::Add;\n\nstruct Foo;\nstruct Bar;\n\n#[derive(Show)]\nstruct FooBar;\n\n#[derive(Show)]\nstruct BarFoo;\n\n// The `Add<T, U>` trait needs two generic parameters:\n// * T is the type of the RHS summand, and\n// * U is the type of the sum\n// This block implements the operation: Foo + Bar = FooBar\nimpl Add<Bar> for Foo {\n type Output = FooBar;\n \n fn add(self, _rhs: Bar) -> FooBar {\n println!(\"> Foo.add(&Bar) was called\");\n\n FooBar\n }\n}\n\n// Addition can be implemented in a non-commutative way\n// This block implements the operation: Bar + Foo = BarFoo\nimpl Add<Foo> for Bar {\n type Output = BarFoo;\n \n fn add(self, _rhs: Foo) -> BarFoo {\n println!(\"> Bar.add(&Foo) was called\");\n\n BarFoo\n }\n}\n\nfn main() {\n println!(\"Foo + Bar = {}\", Foo + Bar);\n println!(\"Bar + Foo = {}\", Bar + Foo);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add file to section 2 of examples\n"
},
{
"from": "gpt",
"value": "use std::mem;\n\n// This function borrows a slice\nfn analyze_slice(slice: &[i32]) {\n println!(\"first element: {}\", slice[0]);\n println!(\"slice has {} elements\", slice.len());\n}\n\nfn main() {\n // Fixed-sized array\n let xs: [i32; 4] = [1, 2, 3, 4];\n\n // All elements can be initialized to same value\n let ys: [i32; 500] = [0; 500];\n\n // Indexing starts at 0\n println!(\"first: {}\", xs[0]);\n println!(\"second: {}\", xs[1]);\n\n // Print length of array\n println!(\"array size: {}\", xs.len());\n\n // Arrays are stack allocated\n println!(\"array occupies {} bytes\", mem::size_of_val(&xs));\n\n // Arrays can automatically be borrowed as slices\n println!(\"borrow the whole array as a slice\");\n analyze_slice(&xs);\n\n // Slices can point to a section of an array\n println!(\"borrow a section of the array as a slice\");\n analyze_slice(&ys[1 .. 4]);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix expected error message in a test.\n\nThe change is a result of the char/string parsing refactor.\n"
},
{
"from": "human",
"value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nstatic s: &'static str =\n \"\\●\" //~ ERROR: unknown string escape\n;\n"
},
{
"from": "gpt",
"value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nstatic s: &'static str =\n \"\\●\" //~ ERROR: unknown character escape\n;\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "examples: Add support for a simple CTAP example\n\nSigned-off-by: Alistair Francis <52ecf00b70a50079ae8d5fa09b9af6904950b63c@wdc.com>\n"
},
{
"from": "gpt",
"value": "#![no_std]\n/// This is a very basic CTAP example\n/// This example only calls the CTAP driver calls, it does not implement CTAP\nuse core::fmt::Write;\nuse libtock::ctap::{CtapRecvBuffer, CtapSendBuffer};\nuse libtock::result::TockResult;\nuse libtock::syscalls;\n\n#[libtock::main]\nasync fn main() -> TockResult<()> {\n let mut drivers = libtock::retrieve_drivers()?;\n let mut console = drivers.console.create_console();\n writeln!(console, \"Starting CTAP example\")?;\n let ctap_driver = drivers.ctap.init_driver()?;\n\n writeln!(console, \"Creating recv buffer\")?;\n let mut recv_buffer = CtapRecvBuffer::default();\n let recv_buffer = ctap_driver.init_recv_buffer(&mut recv_buffer)?;\n writeln!(console, \" done\")?;\n\n writeln!(console, \"Creating send buffer\")?;\n let mut send_buffer = CtapSendBuffer::default();\n let _send_buffer = ctap_driver.init_send_buffer(&mut send_buffer)?;\n writeln!(console, \" done\")?;\n\n let mut temp_buffer = [0; libtock::ctap::RECV_BUFFER_SIZE];\n\n writeln!(console, \"Setting callback and running\")?;\n let mut callback = |_, _| {\n writeln!(console, \"CTAP Complete, printing data\").unwrap();\n recv_buffer.read_bytes(&mut temp_buffer[..]);\n\n for buf in temp_buffer.iter().take(libtock::ctap::RECV_BUFFER_SIZE) {\n write!(console, \"{:x}\", *buf).unwrap();\n }\n\n let _ret = ctap_driver.allow_receive();\n };\n\n let _subscription = ctap_driver.subscribe(&mut callback)?;\n ctap_driver.allow_receive()?;\n\n loop {\n unsafe { syscalls::raw::yieldk() };\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression test for duplicate items in overlapping impls. Note that a regression test already exists for *non*overlapping impls.\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// Test that you cannot define items with the same name in overlapping inherent\n// impl blocks.\n\nstruct Foo;\n\nimpl Foo {\n fn id() {} //~ ERROR E0201\n}\n\nimpl Foo {\n fn id() {}\n}\n\nstruct Bar<T>(T);\n\nimpl<T> Bar<T> {\n fn bar(&self) {} //~ ERROR E0201\n}\n\nimpl Bar<u32> {\n fn bar(&self) {}\n}\n\nstruct Baz<T>(T);\n\nimpl<T: Copy> Baz<T> {\n fn baz(&self) {} //~ ERROR E0201\n}\n\nimpl<T> Baz<Vec<T>> {\n fn baz(&self) {}\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add ExtFmt test for unsigned type\n"
},
{
"from": "human",
"value": "// xfail-boot\n// xfail-stage0\nuse std;\nimport std._str;\n\nfn test(str actual, str expected) {\n log actual;\n log expected;\n check (_str.eq(actual, expected));\n}\n\nfn main() {\n test(#fmt(\"hello %d friends and %s things\", 10, \"formatted\"),\n \"hello 10 friends and formatted things\");\n\n // Simple tests for types\n test(#fmt(\"%d\", 1), \"1\");\n test(#fmt(\"%i\", 2), \"2\");\n test(#fmt(\"%i\", -1), \"-1\");\n test(#fmt(\"%s\", \"test\"), \"test\");\n test(#fmt(\"%b\", true), \"true\");\n test(#fmt(\"%b\", false), \"false\");\n test(#fmt(\"%c\", 'A'), \"A\");\n}\n"
},
{
"from": "gpt",
"value": "// xfail-boot\n// xfail-stage0\nuse std;\nimport std._str;\n\nfn test(str actual, str expected) {\n log actual;\n log expected;\n check (_str.eq(actual, expected));\n}\n\nfn main() {\n test(#fmt(\"hello %d friends and %s things\", 10, \"formatted\"),\n \"hello 10 friends and formatted things\");\n\n // Simple tests for types\n test(#fmt(\"%d\", 1), \"1\");\n test(#fmt(\"%i\", 2), \"2\");\n test(#fmt(\"%i\", -1), \"-1\");\n test(#fmt(\"%u\", 10u), \"10\");\n test(#fmt(\"%s\", \"test\"), \"test\");\n test(#fmt(\"%b\", true), \"true\");\n test(#fmt(\"%b\", false), \"false\");\n test(#fmt(\"%c\", 'A'), \"A\");\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add tests for wrapping integers\n\nSigned-off-by: Matthias Beyer <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@beyermatthias.de>\n"
},
{
"from": "gpt",
"value": "extern crate config;\n\nuse config::*;\n\n#[test]\nfn wrapping_u16() {\n let c = Config::builder()\n .add_source(config::File::from_str(\n r#\"\n [settings]\n port = 66000\n \"#,\n config::FileFormat::Toml,\n ))\n .build()\n .unwrap();\n\n let port: u16 = c.get(\"settings.port\").unwrap();\n assert_eq!(port, 464);\n}\n\n#[test]\nfn nonwrapping_u32() {\n let c = Config::builder()\n .add_source(config::File::from_str(\n r#\"\n [settings]\n port = 66000\n \"#,\n config::FileFormat::Toml,\n ))\n .build()\n .unwrap();\n\n let port: u32 = c.get(\"settings.port\").unwrap();\n assert_eq!(port, 66000);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Update test and un-xfail it\n"
},
{
"from": "human",
"value": "// xfail-test #2587\n// error-pattern: copying a noncopyable value\n\nstruct r {\n let i:int;\n new(i:int) {self.i = i;}\n}\n\nimpl r : Drop {\n fn finalize() {}\n}\n\nfn main() {\n // This can't make sense as it would copy the classes\n let i = move ~[r(0)];\n let j = move ~[r(1)];\n let k = i + j;\n log(debug, j);\n}\n"
},
{
"from": "gpt",
"value": "// error-pattern: copying a noncopyable value\n\nstruct r {\n i:int\n}\n\nfn r(i:int) -> r { r { i: i } }\n\nimpl r : Drop {\n fn finalize() {}\n}\n\nfn main() {\n // This can't make sense as it would copy the classes\n let i = move ~[r(0)];\n let j = move ~[r(1)];\n let k = i + j;\n log(debug, j);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test for incorrect remote type deserializing\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate serde_derive;\n\nmod remote {\n pub struct S(pub u16);\n}\n\n#[derive(Deserialize)] //~ ERROR: mismatched types\n#[serde(remote = \"remote::S\")]\nstruct S(u8); //~^^ expected u16, found u8\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add example of connection using TLS\n"
},
{
"from": "gpt",
"value": "use ldap3::LdapConn;\n\nconst LDAPS_SERVER: &str = \"ldaps://directory.example.com:636\";\nconst LDAP_SERVICE_USER_DN: &str = \"CN=ldapuser,CN=Users,DC=example,DC=com\";\nconst LDAP_SERVICE_USER_PW: &str = \"SuperSecretPassword\";\n\nfn main() {\n\n let ldap = LdapConn::new(LDAPS_SERVER).expect(\"Failed to create handle\");\n\n ldap.simple_bind(LDAP_SERVICE_USER_DN, LDAP_SERVICE_USER_PW).expect(\"Bind error\");\n \n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an example to render without Renderer\n"
},
{
"from": "gpt",
"value": "extern crate sdl2;\n\nuse sdl2::pixels::Color;\nuse sdl2::event::Event;\nuse sdl2::keyboard::Keycode;\nuse sdl2::video::Window;\nuse sdl2::rect::Rect;\nuse std::time::Duration;\n\nconst WINDOW_WIDTH : u32 = 800;\nconst WINDOW_HEIGHT : u32 = 600;\n\n#[derive(Clone, Copy)]\nenum Gradient {\n Red,\n Cyan,\n Green,\n Blue,\n White\n}\n\nfn set_window_gradient(window: &mut Window, event_pump: &sdl2::EventPump, gradient: Gradient) {\n let mut surface = window.surface(event_pump).unwrap();\n for i in 0 .. (WINDOW_WIDTH / 4) {\n let c : u8 = 255 - (i as u8);\n let i = i as i32;\n let color = match gradient {\n Gradient::Red => Color::RGB(c, 0, 0),\n Gradient::Cyan => Color::RGB(0, c, c),\n Gradient::Green => Color::RGB(0, c, 0),\n Gradient::Blue => Color::RGB(0, 0, c),\n Gradient::White => Color::RGB(c, c, c),\n };\n surface.fill_rect(Rect::new(i*4, 0, 4, WINDOW_HEIGHT), color).unwrap();\n }\n surface.finish().unwrap();\n}\n\nfn next_gradient(gradient: Gradient) -> Gradient {\n use Gradient::*;\n match gradient {\n Red => Cyan,\n Cyan => Green,\n Green => Blue,\n Blue => White,\n White => Red,\n }\n}\n\npub fn main() {\n let sdl_context = sdl2::init().unwrap();\n let video_subsystem = sdl_context.video().unwrap();\n \n let mut window = video_subsystem.window(\"rust-sdl2 demo: No Renderer\", WINDOW_WIDTH, WINDOW_HEIGHT)\n .position_centered()\n .build()\n .unwrap();\n let mut event_pump = sdl_context.event_pump().unwrap();\n let mut current_gradient = Gradient::Red;\n set_window_gradient(&mut window, &event_pump, current_gradient);\n 'running: loop {\n let mut keypress : bool = false;\n for event in event_pump.poll_iter() {\n match event {\n Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {\n break 'running\n },\n Event::KeyDown { repeat: false, .. } => {\n keypress = true;\n },\n _ => {}\n }\n }\n if keypress {\n current_gradient = next_gradient(current_gradient);\n set_window_gradient(&mut window, &event_pump, current_gradient);\n }\n ::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for vstore, which already works\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 { V1(int), V0 }\nconst C: &static/[E] = &[V0, V1(0xDEADBEE), V0];\n\nfn main() {\n match C[1] {\n V1(n) => assert(n == 0xDEADBEE),\n _ => die!()\n }\n match C[2] { \n V0 => (),\n _ => die!()\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add example with the code in tutorial 01\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate glium;\nextern crate glutin;\n\nfn main() {\n use glium::{DisplayBuild, Surface};\n let display = glutin::WindowBuilder::new().build_glium().unwrap();\n\n #[derive(Copy)]\n struct Vertex {\n position: [f32; 2],\n }\n\n implement_vertex!(Vertex, position);\n\n let vertex1 = Vertex { position: [-0.5, -0.5] };\n let vertex2 = Vertex { position: [ 0.0, 0.5] };\n let vertex3 = Vertex { position: [ 0.5, -0.25] };\n let shape = vec![vertex1, vertex2, vertex3];\n\n let vertex_buffer = glium::VertexBuffer::new(&display, shape);\n let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);\n\n let vertex_shader_src = r#\"\n #version 110\n\n attribute vec2 position;\n\n void main() {\n gl_Position = vec4(position, 0.0, 1.0);\n }\n \"#;\n\n let fragment_shader_src = r#\"\n #version 110\n\n void main() {\n gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n }\n \"#;\n\n let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None).unwrap();\n\n loop {\n let mut target = display.draw();\n target.clear_color(0.0, 0.0, 1.0, 1.0);\n target.draw(&vertex_buffer, &indices, &program, &glium::uniforms::EmptyUniforms,\n &std::default::Default::default()).unwrap();\n target.finish();\n\n if display.is_closed() {\n break;\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add a test case for linearize_ty_params() and shapes\n"
},
{
"from": "gpt",
"value": "// xfail-test\n\n// Tests that shapes respect linearize_ty_params().\n\ntag option<T> {\n none;\n some(T);\n}\n\ntype smallintmap<T> = @{mutable v: [mutable option<T>]};\n\nfn mk<@T>() -> smallintmap<T> {\n let v: [mutable option<T>] = [mutable];\n ret @{mutable v: v};\n}\n\nfn f<@T,@U>() {\n let sim = mk::<U>();\n log_err sim;\n}\n\nfn main() {\n f::<int,int>();\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rust code for isogram case\n\nIt passed all test cases\n"
},
{
"from": "gpt",
"value": "#![feature(ascii_ctype)]\n\npub fn check(words: &str) -> bool {\n let mut mask = 0u32;\n\n for c in words.chars() {\n if c.is_ascii_alphabetic() {\n let index = c.to_ascii_lowercase() as usize - 'a' as usize;\n\n let v = 1u32 << index;\n if mask & v == v {\n return false;\n }\n\n mask |= v;\n }\n }\n\n true\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression test for write_primval bug.\n"
},
{
"from": "gpt",
"value": "// PrimVals in Miri are represented with 8 bytes (u64) and at the time of writing, the `-x`\n// will sign extend into the entire 8 bytes. Then, if you tried to write the `-x` into\n// something smaller than 8 bytes, like a 4 byte pointer, it would crash in byteorder crate\n// code that assumed only the low 4 bytes would be set. Actually, we were masking properly for\n// everything except pointers before I fixed it, so this was probably impossible to reproduce on\n// 64-bit.\n//\n// This is just intended as a regression test to make sure we don't reintroduce this problem.\n\n#[cfg(target_pointer_width = \"32\")]\nfn main() {\n use std::mem::transmute;\n\n // Make the weird PrimVal.\n let x = 1i32;\n let bad = unsafe { transmute::<i32, *const u8>(-x) };\n\n // Force it through the Memory::write_primval code.\n Box::new(bad);\n}\n\n#[cfg(not(target_pointer_width = \"32\"))]\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add compile-fail test to assert HasDual is sealed\n"
},
{
"from": "gpt",
"value": "extern crate session_types;\n\nuse session_types::HasDual;\n\nstruct CustomProto;\n\nimpl HasDual for CustomProto { //~ ERROR the trait bound `CustomProto: session_types::private::Sealed` is not satisfied\n type Dual = CustomProto;\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add an Rc reference cycle test.\n"
},
{
"from": "human",
"value": "#![feature(custom_attribute, box_syntax)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn rc_cell() -> i32 {\n use std::rc::Rc;\n use std::cell::Cell;\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r.get()\n}\n\n// TODO(tsion): borrow code needs to evaluate string statics via Lvalue::Static\n// #[miri_run]\n// fn rc_refcell() -> i32 {\n// use std::rc::Rc;\n// use std::cell::RefCell;\n// let r = Rc::new(RefCell::new(42));\n// *r.borrow_mut() += 10;\n// let x = *r.borrow();\n// x\n// }\n\n#[miri_run]\nfn arc() -> i32 {\n use std::sync::Arc;\n let a = Arc::new(42);\n *a\n}\n\n#[miri_run]\nfn true_assert() {\n assert_eq!(1, 1);\n}\n"
},
{
"from": "gpt",
"value": "#![feature(custom_attribute, box_syntax)]\n#![allow(dead_code, unused_attributes)]\n\nuse std::cell::{Cell, RefCell};\nuse std::rc::Rc;\nuse std::sync::Arc;\n\n#[miri_run]\nfn rc_cell() -> Rc<Cell<i32>> {\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r\n}\n\n// TODO(tsion): borrow code needs to evaluate string statics via Lvalue::Static\n// TODO(tsion): also requires destructors to run for the second borrow to work\n// #[miri_run]\n// fn rc_refcell() -> i32 {\n// let r = Rc::new(RefCell::new(42));\n// *r.borrow_mut() += 10;\n// let x = *r.borrow();\n// x\n// }\n\n#[miri_run]\nfn arc() -> Arc<i32> {\n let a = Arc::new(42);\n a\n}\n\nstruct Loop(Rc<RefCell<Option<Loop>>>);\n\n#[miri_run]\nfn rc_reference_cycle() -> Loop {\n let a = Rc::new(RefCell::new(None));\n let b = a.clone();\n *a.borrow_mut() = Some(Loop(b));\n Loop(a)\n}\n\n#[miri_run]\nfn true_assert() {\n assert_eq!(1, 1);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add test to new branches\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\nenum Token { LeftParen, RightParen, Plus, Minus, /* etc */ }\n//~^ NOTE variant `Homura` not found here\n\nfn use_token(token: &Token) { unimplemented!() }\n\nfn main() {\n use_token(&Token::Homura);\n //~^ ERROR no variant named `Homura`\n //~| NOTE variant not found in `Token`\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\nenum Token { LeftParen, RightParen, Plus, Minus, /* etc */ }\n//~^ NOTE variant `Homura` not found here\nstruct Struct {\n //~^ NOTE function or associated item `method` not found for this\n //~| NOTE function or associated item `method` not found for this\n //~| NOTE associated item `Assoc` not found for this\n a: usize,\n}\n\nfn use_token(token: &Token) { unimplemented!() }\n\nfn main() {\n use_token(&Token::Homura);\n //~^ ERROR no variant named `Homura`\n //~| NOTE variant not found in `Token`\n Struct::method();\n //~^ ERROR no function or associated item named `method` found for type\n //~| NOTE function or associated item not found in `Struct`\n Struct::method;\n //~^ ERROR no function or associated item named `method` found for type\n //~| NOTE function or associated item not found in `Struct`\n Struct::Assoc;\n //~^ ERROR no associated item named `Assoc` found for type `Struct` in\n //~| NOTE associated item not found in `Struct`\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Return of basic S3 tests.\n"
},
{
"from": "human",
"value": "#![cfg(feature = \"s3\")]\n\nextern crate env_logger;\n#[macro_use]\nextern crate log;\nextern crate time;\n\n#[macro_use]\nextern crate rusoto;\n\nuse rusoto::{DefaultCredentialsProvider, Region};\nuse rusoto::s3::{S3Error, S3Helper};\n\n#[test]\nfn all_s3_tests() {\n let _ = env_logger::init();\n info!(\"s3 integration tests starting up.\");\n let mut s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);\n\n match s3_list_buckets_tests(&mut s3) {\n Ok(_) => { info!(\"Everything worked for S3 list buckets.\"); },\n Err(err) => { info!(\"Got error in s3 list buckets: {}\", err); }\n }\n}\n\nfn s3_list_buckets_tests(s3: &mut S3Helper<DefaultCredentialsProvider>) -> Result<(), S3Error> {\n let response = try!(s3.list_buckets());\n info!(\"Got list of buckets: {:?}\", response);\n for q in response.buckets {\n info!(\"Existing bucket: {:?}\", q.name);\n }\n\n Ok(())\n}\n"
},
{
"from": "gpt",
"value": "#![cfg(feature = \"s3\")]\n\nextern crate env_logger;\n#[macro_use]\nextern crate log;\nextern crate time;\n\n#[macro_use]\nextern crate rusoto;\n\nuse std::io::Read;\nuse std::fs::File;\nuse rusoto::{DefaultCredentialsProvider, Region};\nuse rusoto::s3::S3Helper;\n\n#[test]\nfn list_buckets_tests() {\n let _ = env_logger::init();\n let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);\n let response = s3.list_buckets().unwrap();\n info!(\"Got list of buckets: {:?}\", response);\n for q in response.buckets {\n info!(\"Existing bucket: {:?}\", q.name);\n }\n}\n\n#[test]\nfn put_object_test() {\n let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);\n let mut f = File::open(\"tests/sample-data/no_credentials\").unwrap();\n let mut contents : Vec<u8> = Vec::new();\n match f.read_to_end(&mut contents) {\n Err(why) => panic!(\"Error opening file to send to S3: {}\", why),\n Ok(_) => {\n s3.put_object(\"rusototester\", \"no_credentials\", &contents).unwrap();\n }\n }\n}\n\n// Dependent on the file being there or it'll break.\n#[test]\nfn get_object_test() {\n let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);\n s3.get_object(\"rusototester\", \"no_credentials2\").unwrap();\n}\n\n#[test]\nfn delete_object_test() {\n let s3 = S3Helper::new(DefaultCredentialsProvider::new().unwrap(), Region::UsWest2);\n s3.delete_object(\"rusototester\", \"no_credentials\").unwrap();\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Implement a test for the Drop trait on a generic struct. a=test-only\n"
},
{
"from": "gpt",
"value": "struct S<T> {\n x: T\n}\n\nimpl<T> S<T> : core::ops::Drop {\n fn finalize() {\n io::println(\"bye\");\n }\n}\n\nfn main() {\n let x = S { x: 1 };\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "examples: Add example for storing file feature\n"
},
{
"from": "gpt",
"value": "extern crate fruently;\nuse std::env;\nuse fruently::fluent::Fluent;\nuse fruently::retry_conf::RetryConf;\nuse std::collections::HashMap;\nuse fruently::forwardable::MsgpackForwardable;\n\nfn main() {\n let home = env::home_dir().unwrap();\n let file = home.join(\"buffer\");\n let conf = RetryConf::new().store_file(file.clone()).max(5).multiplier(2_f64);\n let mut obj: HashMap<String, String> = HashMap::new();\n obj.insert(\"name\".to_string(), \"fruently\".to_string());\n let fruently = Fluent::new_with_conf(\"noexistent.local:24224\", \"test\", conf);\n match fruently.post(&obj) {\n Err(e) => println!(\"{:?}\", e),\n Ok(_) => {\n assert!(file.exists());\n return\n },\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add concrete test for square array\n"
},
{
"from": "gpt",
"value": "extern crate fitsio;\n\nuse fitsio::FitsFile;\n\n#[test]\nfn test_square_array() {\n let filename = \"../testdata/square_array.fits\";\n let mut f = FitsFile::open(filename).unwrap();\n let phdu = f.primary_hdu().unwrap();\n\n let ranges = vec![&(1..3), &(2..4)];\n let data: Vec<u32> = phdu.read_region(&mut f, &ranges).unwrap();\n assert_eq!(data, vec![11, 12, 16, 17]);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add compile-fail test for invalid cfg predicate in attribute\n\nRefs #31495\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#[cfg(foo(bar))] //~ ERROR invalid predicate `foo`\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an xfailed test for bogus vector addition of typarams\n"
},
{
"from": "gpt",
"value": "// xfail-test\n// expected error: mismatched kinds\n\nresource r(i: @mutable int) {\n *i = *i + 1;\n}\n\nfn f<@T>(i: [T], j: [T]) {\n // Shouldn't be able to do this copy of j\n let k = i + j;\n}\n\nfn main() {\n let i1 = @mutable 0;\n let i2 = @mutable 1;\n let r1 <- [~r(i1)];\n let r2 <- [~r(i2)];\n f(r1, r2);\n log_err *i1;\n log_err *i2;\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix a stack to use the new .to_c_str() api\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\nuse std::str;\n\nmod libc {\n #[abi = \"cdecl\"]\n #[nolink]\n extern {\n pub fn atol(x: *u8) -> int;\n pub fn atoll(x: *u8) -> i64;\n }\n}\n\nfn atol(s: ~str) -> int {\n s.as_imm_buf(|x, _len| unsafe { libc::atol(x) })\n}\n\nfn atoll(s: ~str) -> i64 {\n s.as_imm_buf(|x, _len| unsafe { libc::atoll(x) })\n}\n\npub fn main() {\n unsafe {\n assert_eq!(atol(~\"1024\") * 10, atol(~\"10240\"));\n assert!((atoll(~\"11111111111111111\") * 10i64)\n == atoll(~\"111111111111111110\"));\n }\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\nuse std::str;\n\nmod libc {\n #[abi = \"cdecl\"]\n #[nolink]\n extern {\n pub fn atol(x: *u8) -> int;\n pub fn atoll(x: *u8) -> i64;\n }\n}\n\nfn atol(s: ~str) -> int {\n s.to_c_str().with_ref(|x| unsafe { libc::atol(x as *u8) })\n}\n\nfn atoll(s: ~str) -> i64 {\n s.to_c_str().with_ref(|x| unsafe { libc::atoll(x as *u8) })\n}\n\npub fn main() {\n unsafe {\n assert_eq!(atol(~\"1024\") * 10, atol(~\"10240\"));\n assert!((atoll(~\"11111111111111111\") * 10i64)\n == atoll(~\"111111111111111110\"));\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test that multiple wrappers created from a handle share a ref count\n"
},
{
"from": "gpt",
"value": "/* Copyright 2015 Jordan Miner\n *\n * Licensed under the MIT license <LICENSE or\n * http://opensource.org/licenses/MIT>. This file may not be copied,\n * modified, or distributed except according to those terms.\n */\n\nextern crate clear_coat;\n\nuse std::ptr;\nuse std::rc::Rc;\nuse clear_coat::*;\nuse clear_coat::common_attrs_cbs::*;\n\n// Tests that creating multiple control wrappers from the same *mut Ihandle will share\n// a reference count.\n\n#[test]\nfn test_deduplication() {\n let x = Rc::new(5);\n let x2 = x.clone();\n let dialog = Dialog::new(None);\n dialog.enter_window().add_callback(move || println!(\"{}\", *x2));\n let handle = dialog.handle();\n let dialog2 = unsafe { Dialog::from_handle(handle) };\n let dialog3 = unsafe { Dialog::from_handle(handle) };\n let x = Rc::try_unwrap(x).unwrap_err();\n drop(dialog);\n let x = Rc::try_unwrap(x).unwrap_err();\n drop(dialog3);\n let x = Rc::try_unwrap(x).unwrap_err();\n drop(dialog2);\n let _ = Rc::try_unwrap(x).unwrap();\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add tests for checking for extraneous leading newlines (or lack thereof)\n\nCouldn't find a better place to put this (the \"valid\" and \"invalid\"\ntests are just for parser) so I made a new test module\n"
},
{
"from": "gpt",
"value": "extern crate rustc_serialize;\nextern crate toml;\nuse toml::encode_str;\n\n#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]\nstruct User {\n pub name: String,\n pub surname: String,\n}\n\n#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]\nstruct Users {\n pub user: Vec<User>,\n}\n\n#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]\nstruct TwoUsers {\n pub user0: User,\n pub user1: User,\n}\n\n#[test]\nfn no_unnecessary_newlines_array() {\n assert!(!encode_str(&Users {\n user: vec![\n User {\n name: \"John\".to_string(),\n surname: \"Doe\".to_string(),\n },\n User {\n name: \"Jane\".to_string(),\n surname: \"Dough\".to_string(),\n },\n ],\n })\n .starts_with(\"\\n\"));\n}\n\n#[test]\nfn no_unnecessary_newlines_table() {\n assert!(!encode_str(&TwoUsers {\n user0: User {\n name: \"John\".to_string(),\n surname: \"Doe\".to_string(),\n },\n user1: User {\n name: \"Jane\".to_string(),\n surname: \"Dough\".to_string(),\n },\n })\n .starts_with(\"\\n\"));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Duplicate test for type conversion with unsigned int\n\nThis patch duplicates the test that was done with indexmap here with the\nnormal HashMap from std.\n\nSigned-off-by: Matthias Beyer <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@beyermatthias.de>\n"
},
{
"from": "gpt",
"value": "#![cfg(not(feature = \"preserve_order\"))]\n\n#[derive(serde::Deserialize, Eq, PartialEq, Debug)]\nstruct Container<T> {\n inner: T,\n}\n\n#[derive(serde::Deserialize, Eq, PartialEq, Debug)]\nstruct Unsigned {\n unsigned: u16,\n}\n\nimpl Default for Unsigned {\n fn default() -> Self {\n Self { unsigned: 128 }\n }\n}\n\nimpl From<Unsigned> for config::ValueKind {\n fn from(unsigned: Unsigned) -> Self {\n let mut properties = std::collections::HashMap::new();\n properties.insert(\n \"unsigned\".to_string(),\n config::Value::from(unsigned.unsigned),\n );\n\n Self::Table(properties)\n }\n}\n\n#[test]\nfn test_deser_unsigned_int_hm() {\n let container = Container {\n inner: Unsigned::default(),\n };\n\n let built = config::Config::builder()\n .set_default(\"inner\", Unsigned::default())\n .unwrap()\n .build()\n .unwrap()\n .try_deserialize::<Container<Unsigned>>()\n .unwrap();\n\n assert_eq!(container, built);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add regression tests from fuzzing test cases.\n\nThis is the test case from frewsxcv's fuzzing work,\ngenerated by American Fuzzy Lop's rust support.\n\nhttps://github.com/mozilla/mp4parse-rust/issues/2\n"
},
{
"from": "gpt",
"value": "// Regression tests from American Fuzzy Lop test cases.\n\n// 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 https://mozilla.org/MPL/2.0/.\n\nextern crate mp4parse;\n\nuse std::io::Cursor;\n\n/// https://github.com/mozilla/mp4parse-rust/issues/2\n#[test]\nfn fuzz_2() {\n let mut c = Cursor::new(b\"\\x00\\x00\\x00\\x04\\xa6\\x00\\x04\\xa6\".to_vec());\n let mut context = mp4parse::MediaContext::new();\n let _ = mp4parse::read_box(&mut c, &mut context);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for errors unifying an integer variable with a float variable\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 let mut x = 2;\n x = 5.0;\n//~^ ERROR expected `_`, found `_` (expected integral variable, found floating-point variable)\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add a test that function argument patterns take in the expected type. r=test-only\n"
},
{
"from": "gpt",
"value": "fn main() {\n let f: fn((int,int)) = |(x, y)| {\n assert x == 1;\n assert y == 2;\n };\n f((1, 2));\n}\n\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add counting up with line clearing example\n"
},
{
"from": "gpt",
"value": "use std::io::timer;\nuse std::io::stdio;\n\nfn main() {\n stdio::print(\"Loading...\");\n stdio::flush();\n timer::sleep(1000);\n for num in range(0, 1000) {\n stdio::print(\"\\r\\x1b[K\" + num.to_str());\n stdio::flush();\n timer::sleep(100);\n }\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a regression test for use of unexported fully-qualified paths\n\nAn unexported foo.baz can't be resolved from inside foo when called as foo.baz\ninstead of just baz. This behavior may want to change eventually.\n"
},
{
"from": "gpt",
"value": "// xfail-boot\n// error-pattern: unresolved name\n\n// In this test baz isn't resolved when called as foo.baz even though\n// it's called from inside foo. This is somewhat surprising and may\n// want to change eventually.\n\nmod foo {\n\n export bar;\n\n fn bar() {\n foo.baz();\n }\n\n fn baz() {\n }\n}\n\nfn main() {\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add tests for ensuring docblock headings.\n"
},
{
"from": "gpt",
"value": "#![crate_name = \"foo\"]\n\n// @has foo/trait.Read.html\n// @has - '//h2' 'Trait examples'\n/// # Trait examples\npub trait Read {\n // @has - '//h5' 'Function examples'\n /// # Function examples\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, ()>;\n}\n\npub struct Foo;\n\n// @has foo/struct.Foo.html\nimpl Foo {\n // @has - '//h5' 'Implementation header'\n /// # Implementation header\n pub fn bar(&self) -> usize {\n 1\n }\n}\n\nimpl Read for Foo {\n // @has - '//h5' 'Trait implementation header'\n /// # Trait implementation header\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, ()> {\n Ok(1)\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add piping code for Commands\n\nThis does piping properly, but it is not integrated with the rest of\nthe application.\n"
},
{
"from": "gpt",
"value": "use std::process::{Stdio, Command, Child};\nuse std::os::unix::io::{FromRawFd, IntoRawFd};\n\npub fn pipe(commands: &mut [Command]) {\n if commands.len() == 0 {\n return;\n }\n let end = commands.len() - 1;\n for command in &mut commands[..end] {\n command.stdout(Stdio::piped());\n }\n let mut prev: Option<Child> = None;\n for command in commands {\n if let Some(child) = prev {\n unsafe {\n command.stdin(Stdio::from_raw_fd(child.stdout.unwrap().into_raw_fd()));\n }\n }\n prev = Some(command.spawn().expect(\"\"));\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for 'std' crate being public\n"
},
{
"from": "gpt",
"value": "// The 'std' crates should always be implicitly public,\n// without having to pass any compiler arguments\n\n// run-pass\n\n#![feature(public_private_dependencies)]\n#![deny(external_private_dependency)]\n\npub struct PublicType {\n pub field: Option<u8>\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for const endianess conversion\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#![feature(const_int_ops)]\n\nconst BE_U32: u32 = 55u32.to_be();\nconst LE_U32: u32 = 55u32.to_le();\nconst BE_U128: u128 = 999999u128.to_be();\nconst LE_I128: i128 = -999999i128.to_le();\n\nfn main() {\n assert_eq!(BE_U32, 55u32.to_be());\n assert_eq!(LE_U32, 55u32.to_le());\n assert_eq!(BE_U128, 999999u128.to_be());\n assert_eq!(LE_I128, -999999i128.to_le());\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Update rustc-serialize import to new syntax\n"
},
{
"from": "human",
"value": "#![feature(core)]\n#![feature(io)]\n#![feature(std_misc)]\n#![feature(step_by)]\n#![feature(test)]\n\nextern crate byteorder;\nextern crate flate2;\nextern crate nbt;\nextern crate \"rustc-serialize\" as rustc_serialize;\nextern crate test;\nextern crate time;\nextern crate uuid;\n\npub mod packet;\npub mod proto;\npub mod types;\nmod util;\n"
},
{
"from": "gpt",
"value": "#![feature(core)]\n#![feature(io)]\n#![feature(std_misc)]\n#![feature(step_by)]\n#![feature(test)]\n\nextern crate byteorder;\nextern crate flate2;\nextern crate nbt;\nextern crate rustc_serialize;\nextern crate test;\nextern crate time;\nextern crate uuid;\n\npub mod packet;\npub mod proto;\npub mod types;\nmod util;\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add Rust solutin for balanced brackets\n"
},
{
"from": "gpt",
"value": "use std::collections::HashMap;\n\nfn balanced_brackets(s: &str) -> bool {\n // Use a vector as a stack\n let mut stack = Vec::new();\n\n let mut matches = HashMap::new();\n matches.insert(')', '(');\n matches.insert(']', '[');\n matches.insert('}', '{');\n\n for c in s.chars() {\n match c {\n '(' | '[' | '{' => stack.push(c),\n ')' | ']' | '}' => {\n let prev = stack.pop();\n match matches.get(&c) {\n Some(prev) => (),\n _ => unreachable!()\n }\n }\n _ => return false, // Not a bracket\n }\n }\n true\n}\n\nfn main() {\n assert_eq!(true, balanced_brackets(\"{([][[[][]({})]])}\"));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Make rust-la build with latest rust.\n"
},
{
"from": "gpt",
"value": "// Copyright 2013 The Servo Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution.\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\n/// Trait for testing approximate equality\npub trait ApproxEq<Eps> {\n fn approx_epsilon() -> Eps;\n fn approx_eq(&self, other: &Self) -> bool;\n fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;\n}\n\nimpl ApproxEq<f32> for f32 {\n #[inline]\n fn approx_epsilon() -> f32 { 1.0e-6 }\n\n #[inline]\n fn approx_eq(&self, other: &f32) -> bool {\n self.approx_eq_eps(other, &1.0e-6)\n }\n\n #[inline]\n fn approx_eq_eps(&self, other: &f32, approx_epsilon: &f32) -> bool {\n (*self - *other).abs() < *approx_epsilon\n }\n}\n\n\nimpl ApproxEq<f64> for f64 {\n #[inline]\n fn approx_epsilon() -> f64 { 1.0e-6 }\n\n #[inline]\n fn approx_eq(&self, other: &f64) -> bool {\n self.approx_eq_eps(other, &1.0e-6)\n }\n \n #[inline]\n fn approx_eq_eps(&self, other: &f64, approx_epsilon: &f64) -> bool {\n (*self - *other).abs() < *approx_epsilon\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add tests involving Rc, Arc, and Cell.\n"
},
{
"from": "gpt",
"value": "#![feature(custom_attribute, box_syntax)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn rc_cell() -> i32 {\n use std::rc::Rc;\n use std::cell::Cell;\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r.get()\n}\n\n#[miri_run]\nfn arc() -> i32 {\n use std::sync::Arc;\n let a = Arc::new(42);\n *a\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test: Add test that aux2bib runs\n\nThis just tests that aux2bib exists and runs. I couldn't find\ndocumentation on doing tests of binaries, but borrowed from what ripgrep\ndoes.\n\nThis test may break in the future if Cargo changes where binaries for\ntests are built.\n"
},
{
"from": "gpt",
"value": "use std::env;\nuse std::process::Command;\nuse std::path::PathBuf;\n\nfn get_bin_dir() -> PathBuf {\n env::current_exe()\n .expect(\"test bin's directory\")\n .parent()\n .expect(\"test bin's parent directory\")\n .parent()\n .expect(\"executable's directory\")\n .to_path_buf()\n}\n\nfn cmd_aux2bib() -> Command {\n let path = get_bin_dir().join(\"aux2bib\");\n if !path.is_file() {\n panic!(\"aux2bib binary not found\");\n }\n let mut cmd = Command::new(path);\n\n cmd.env_clear();\n\n cmd\n}\n\n#[test]\nfn aux2bib_runs() {\n let mut cmd = cmd_aux2bib().arg(\"--help\").spawn().expect(\n \"Failed to execute aux2bib\",\n );\n\n let error_code = cmd.wait().expect(\"Failed to wait on aux2bib\");\n\n assert!(error_code.success());\n\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add an example for counted flags.\n\nClose #56.\n"
},
{
"from": "gpt",
"value": "extern crate serialize;\nextern crate docopt;\n\nuse docopt::Docopt;\n\n// This shows how to implement multiple levels of verbosity.\n//\n// When you have multiple patterns, I think the only way to carry the\n// repeated flag through all of them is to specify it for each pattern\n// explicitly.\n//\n// This is unfortunate.\nstatic USAGE: &'static str = \"\nUsage: cp [options] [-v | -vv | -vvv] <source> <dest>\n cp [options] [-v | -vv | -vvv] <source>... <dir>\n\nOptions:\n -a, --archive Copy everything.\n -v, --verbose Show extra log output.\n\";\n\n#[deriving(Decodable, Show)]\nstruct Args {\n arg_source: Vec<String>,\n arg_dest: String,\n arg_dir: String,\n flag_archive: bool,\n flag_verbose: uint,\n}\n\nfn main() {\n let args: Args = Docopt::new(USAGE)\n .and_then(|d| d.decode())\n .unwrap_or_else(|e| e.exit());\n println!(\"{}\", args);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Check that `chdir` fails for non-utf8 paths\n"
},
{
"from": "gpt",
"value": "// compile-flags: -Zmiri-disable-isolation\n\nextern {\n pub fn chdir(dir: *const u8) -> i32;\n}\n\nfn main() {\n let path = vec![0xc3u8, 0x28, 0];\n // test that `chdir` errors with invalid utf-8 path\n unsafe { chdir(path.as_ptr()) }; //~ ERROR is not a valid utf-8 string\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Solve Salary with Bonus in rust\n"
},
{
"from": "gpt",
"value": "use std::io;\n\nfn main() {\n let mut input_a = String::new();\n let mut input_b = String::new();\n let mut input_c = String::new();\n\n if let Err(_e) = io::stdin().read_line(&mut input_a){}\n let _a: String = input_a.trim().parse().unwrap();\n\n if let Err(_e) = io::stdin().read_line(&mut input_b){}\n let b: f64 = input_b.trim().parse().unwrap();\n\n if let Err(_e) = io::stdin().read_line(&mut input_c){}\n let c: f64 = input_c.trim().parse().unwrap();\n\n println!(\"TOTAL = R$ {:.2}\", b + c * 0.15);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add solution to problem 29\n"
},
{
"from": "gpt",
"value": "#![feature(core)]\n#[macro_use] extern crate libeuler;\nextern crate num;\n\nuse num::traits::FromPrimitive;\nuse num::bigint::BigInt;\nuse num::pow;\n\nuse std::collections::HashSet;\n\n/// Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:\n///\n/// 2^2=4, 2^3=8, 2^4=16, 2^5=32\n/// 3^2=9, 3^3=27, 3^4=81, 3^5=243\n/// 4^2=16, 4^3=64, 4^4=256, 4^5=1024\n/// 5^2=25, 5^3=125, 5^4=625, 5^5=3125\n///\n/// If they are then placed in numerical order, with any repeats removed, we get the following\n/// sequence of 15 distinct terms:\n///\n/// 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125\n///\n/// How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?\nfn main() {\n solutions! {\n inputs: (max: i32 = 100)\n sol naive {\n let mut set = HashSet::new();\n for a in 2..max+1 {\n for b in 2..max+1 {\n set.insert(pow(BigInt::from_i32(a).unwrap(), b as usize));\n }\n }\n\n set.len()\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rust code for allergies case\n\nI don't know how to exchange enum type and u32 type\n"
},
{
"from": "gpt",
"value": "#[derive(Debug, Clone, PartialEq)]\npub enum Allergen {\n Eggs = 0x0000_0001,\n Peanuts = 0x0000_0002,\n Shellfish = 0x0000_0004,\n Strawberries = 0x0000_0008,\n Tomatoes = 0x0000_0010,\n Chocolate = 0x0000_0020,\n Pollen = 0x0000_0040,\n Cats = 0x0000_0080,\n}\n\n#[derive(Debug)]\npub struct Allergies {\n result: u32,\n}\n\nimpl Allergies {\n pub fn new(score: u32) -> Allergies {\n Allergies { result: score }\n }\n\n pub fn is_allergic_to(&self, item: &Allergen) -> bool {\n self.result & (*item).clone() as u32 != 0\n }\n\n pub fn allergies(&self) -> Vec<Allergen> {\n let mut result: Vec<Allergen> = Vec::new();\n\n let value = self.result;\n\n if value & Allergen::Eggs as u32 == Allergen::Eggs as u32 {\n result.push(Allergen::Eggs);\n }\n\n if value & Allergen::Peanuts as u32 == Allergen::Peanuts as u32 {\n result.push(Allergen::Peanuts);\n }\n\n if value & Allergen::Shellfish as u32 == Allergen::Shellfish as u32 {\n result.push(Allergen::Shellfish);\n }\n\n if value & Allergen::Strawberries as u32 == Allergen::Strawberries as u32 {\n result.push(Allergen::Strawberries);\n }\n\n if value & Allergen::Tomatoes as u32 == Allergen::Tomatoes as u32 {\n result.push(Allergen::Tomatoes);\n }\n\n if value & Allergen::Chocolate as u32 == Allergen::Chocolate as u32 {\n result.push(Allergen::Chocolate);\n }\n\n if value & Allergen::Pollen as u32 == Allergen::Pollen as u32 {\n result.push(Allergen::Pollen);\n }\n\n if value & Allergen::Cats as u32 == Allergen::Cats as u32 {\n result.push(Allergen::Cats)\n }\n\n println!(\"{:?}\", result);\n\n result\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "test(Rust): Add test for sizeof structs and enums\n"
},
{
"from": "gpt",
"value": "//! Print sizes of structs and enums\n//!\n//! Run with `cargo test sizes -- --nocapture`\n//! to get the printed output.\n\nuse stencila_schema::*;\n\nmacro_rules! sizeof {\n ($type:ident) => {\n {\n let size = std::mem::size_of::<$type>();\n println!(\"{}: {}\", stringify!($type), size);\n size\n }\n };\n}\n\n#[test]\nfn sizes() {\n sizeof!(Primitive);\n\n sizeof!(ArrayValidator);\n sizeof!(Article);\n sizeof!(AudioObject);\n sizeof!(BooleanValidator);\n sizeof!(Brand);\n sizeof!(CitationIntentEnumeration);\n sizeof!(Cite);\n sizeof!(CiteGroup);\n sizeof!(Claim);\n sizeof!(Code);\n sizeof!(CodeBlock);\n sizeof!(CodeChunk);\n sizeof!(CodeError);\n sizeof!(CodeExpression);\n sizeof!(CodeFragment);\n sizeof!(Collection);\n sizeof!(Comment);\n sizeof!(ConstantValidator);\n sizeof!(ContactPoint);\n sizeof!(CreativeWork);\n sizeof!(Datatable);\n sizeof!(DatatableColumn);\n sizeof!(Date);\n sizeof!(DefinedTerm);\n sizeof!(Delete);\n sizeof!(Emphasis);\n sizeof!(EnumValidator);\n sizeof!(Enumeration);\n sizeof!(Figure);\n sizeof!(Function);\n sizeof!(Grant);\n sizeof!(Heading);\n sizeof!(ImageObject);\n sizeof!(Include);\n sizeof!(IntegerValidator);\n sizeof!(Link);\n sizeof!(List);\n sizeof!(ListItem);\n sizeof!(Mark);\n sizeof!(Math);\n sizeof!(MathBlock);\n sizeof!(MathFragment);\n sizeof!(MediaObject);\n sizeof!(MonetaryGrant);\n sizeof!(NontextualAnnotation);\n sizeof!(Note);\n sizeof!(NumberValidator);\n sizeof!(Organization);\n sizeof!(Paragraph);\n sizeof!(Parameter);\n sizeof!(Periodical);\n sizeof!(Person);\n sizeof!(PostalAddress);\n sizeof!(Product);\n sizeof!(PropertyValue);\n sizeof!(PublicationIssue);\n sizeof!(PublicationVolume);\n sizeof!(Quote);\n sizeof!(QuoteBlock);\n sizeof!(Review);\n sizeof!(SoftwareApplication);\n sizeof!(SoftwareEnvironment);\n sizeof!(SoftwareSession);\n sizeof!(SoftwareSourceCode);\n sizeof!(StringValidator);\n sizeof!(Strong);\n sizeof!(Subscript);\n sizeof!(Superscript);\n sizeof!(Table);\n sizeof!(TableCell);\n sizeof!(TableRow);\n sizeof!(ThematicBreak);\n sizeof!(Thing);\n sizeof!(TupleValidator);\n sizeof!(Validator);\n sizeof!(Variable);\n sizeof!(VideoObject);\n sizeof!(VolumeMount);\n\n sizeof!(InlineContent);\n sizeof!(BlockContent);\n\n sizeof!(CreativeWork);\n sizeof!(CreativeWorkTypes);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test extracted from rand, checking that StorageDead kills loans\n\nLike \"call-kills-loans\", Polonius didn't know about some `killed` facts.\n"
},
{
"from": "gpt",
"value": "// Whenever a `StorageDead` MIR statement destroys a value `x`,\n// we should kill all loans of `x`. This is extracted from `rand 0.4.6`,\n// is correctly accepted by NLL but was incorrectly rejected by\n// Polonius because of these missing `killed` facts.\n\n// build-pass\n// compile-flags: -Z borrowck=mir -Z polonius\n// ignore-compare-mode-nll\n\nuse std::{io, mem};\nuse std::io::Read;\n\nfn fill(r: &mut Read, mut buf: &mut [u8]) -> io::Result<()> {\n while buf.len() > 0 {\n match r.read(buf).unwrap() {\n 0 => return Err(io::Error::new(io::ErrorKind::Other,\n \"end of file reached\")),\n n => buf = &mut mem::replace(&mut buf, &mut [])[n..],\n // ^- Polonius had multiple errors on the previous line (where NLL has none)\n // as it didn't know `buf` was killed here, and would\n // incorrectly reject both the borrow expression, and the assignment.\n }\n }\n Ok(())\n}\n\nfn main() {\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add skeleton code for HashJoinExec.\n"
},
{
"from": "gpt",
"value": "use common::types::Ty;\nuse driver::DriverContext;\nuse super::{Executor, ExecutorFactory};\n\npub struct HashJoinExecFactory \n{\n\ttypes: Vec<Ty>\n}\n\nimpl HashJoinExecFactory\n{\n\tpub fn new(lf: Box<ExecutorFactory>, rf: Box<ExecutorFactory>) -> HashJoinExecFactory\n\t{\n\t\tHashJoinExecFactory {\n\t\t\ttypes: Vec::new()\n\t\t}\n\t}\n}\n\nimpl ExecutorFactory for HashJoinExecFactory\n{\n\tfn create(&self, ctx: &DriverContext) -> Option<Box<Executor>>\n\t{\n\t\tNone\n\t}\n\t\n\tfn types(&self) -> &Vec<Ty>\n\t{\n\t\t&self.types\n\t}\n}\n\npub struct HashJoinExec;"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add missing file from previous commit."
},
{
"from": "gpt",
"value": "use hyper::net::Openssl;\nuse openssl::crypto::pkey::PKey;\nuse openssl::ssl::{SslContext, SslMethod, SSL_VERIFY_NONE};\nuse openssl::ssl::error::SslError;\nuse openssl::x509::X509;\nuse std::io::Cursor;\nuse std::sync::Arc;\n\nstatic SPOTILOCAL_CERT : &'static [u8] = include_bytes!(\"data/spotilocal.cert\");\nstatic SPOTILOCAL_KEY : &'static [u8] = include_bytes!(\"data/spotilocal.key\");\n\npub fn ssl_context() -> Result<Openssl, SslError> {\n let cert = try!(X509::from_pem(&mut Cursor::new(SPOTILOCAL_CERT)));\n let key = try!(PKey::private_key_from_pem(&mut Cursor::new(SPOTILOCAL_KEY)));\n\n let mut ctx = try!(SslContext::new(SslMethod::Sslv23));\n try!(ctx.set_cipher_list(\"DEFAULT\"));\n try!(ctx.set_private_key(&key));\n try!(ctx.set_certificate(&cert));\n ctx.set_verify(SSL_VERIFY_NONE, None);\n Ok(Openssl { context: Arc::new(ctx) })\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Prepare code for a flat_map test\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate nom;\n\nuse nom::{IResult, Needed, alphanumeric, is_alphanumeric};\n\nnamed!(certain_length<&[u8], &[u8]>, take!(10));\n\nnamed!(value<&[u8], &[u8]>,\n take_while!(is_alphanumeric));\n\nnamed!(comment<&[u8], &[u8]>,\n do_parse!(\n tag!(\"/\") >>\n comment: alphanumeric >>\n (comment)\n ));\n\nnamed!(record<&[u8], (&[u8], Option<&[u8]>)>,\n do_parse!(\n v: value >>\n c: opt!(comment) >>\n ((v, c))\n ));\n\n#[test]\nfn certain_length_test() {\n assert_eq!(certain_length(&b\"0123456789\"[..]), IResult::Done(&b\"\"[..], &b\"0123456789\"[..]));\n assert_eq!(certain_length(&b\"012345678\"[..]), IResult::Incomplete(Needed::Size(10)));\n assert_eq!(certain_length(&b\"abcdefghijk\"[..]), IResult::Done(&b\"k\"[..], &b\"abcdefghij\"[..]));\n}\n\n#[test]\nfn value_test() {\n assert_eq!(value(&b\"\"[..]),\n IResult::Done(&b\"\"[..], &b\"\"[..]));\n assert_eq!(value(&b\"a\"[..]),\n IResult::Done(&b\"\"[..], &b\"a\"[..]));\n assert_eq!(value(&b\"ab\"[..]),\n IResult::Done(&b\"\"[..], &b\"ab\"[..]));\n assert_eq!(value(&b\"abc\"[..]),\n IResult::Done(&b\"\"[..], &b\"abc\"[..]));\n}\n\n#[test]\nfn comment_test() {\n assert_eq!(comment(&b\"/a\"[..]), IResult::Done(&b\"\"[..], &b\"a\"[..]));\n assert_eq!(comment(&b\"/ab\"[..]), IResult::Done(&b\"\"[..], &b\"ab\"[..]));\n assert_eq!(comment(&b\"/abc\"[..]), IResult::Done(&b\"\"[..], &b\"abc\"[..]));\n}\n\n#[test]\nfn record_test() {\n assert_eq!(record(&b\"abcd/123\"[..]),\n IResult::Done(&b\"\"[..], (&b\"abcd\"[..], Option::Some(&b\"123\"[..]))));\n assert_eq!(record(&b\"abcd/123 \"[..]),\n IResult::Done(&b\" \"[..], (&b\"abcd\"[..], Option::Some(&b\"123\"[..]))));\n assert_eq!(record(&b\"abcd \"[..]),\n IResult::Done(&b\" \"[..], (&b\"abcd\"[..], Option::None)));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add enum representing OSC types\n"
},
{
"from": "gpt",
"value": "// see OSC Type Tag String: http://opensoundcontrol.org/spec-1_0\n// padding: zero bytes (n*4)\npub enum OscType {\n OscInt(i32),\n OscFloat(f32),\n OscString(String), // padding\n OscBlob(Vec<u8>), // padding\n OscTimetag(u64),\n // nonstandard argument types\n // ignore them if not implemented\n OscInt64(i64), // big-endian\n OscDouble(u64),\n OscChar(u8), // padding\n OscColor(u32), // RGBA\n OscMidi(OscMidiType),\n OscTrue,\n OscFalse,\n OscNil,\n OscInf,\n OscArray(Vec<OscType>),\n}\n\npub struct OscMidiType {\n port: u8,\n status: u8,\n data1: u8, // maybe use an enum for data?\n data2: u8,\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Introduce a testcase for conditional compilation via attributes\n\nIssue #489\n"
},
{
"from": "gpt",
"value": "// xfail-stage0\n// xfail-stage1\n// xfail-stage2\n\n// Since the bogus configuration isn't defined main will just be\n// parsed, but nothing further will be done with it\n#[cfg(bogus)]\nfn main() { fail }\n\nfn main() {}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rust code for rotational-cipher\n\nIt passed all testcases\n"
},
{
"from": "gpt",
"value": "#![feature(ascii_ctype)]\nuse std::ascii::AsciiExt;\n\npub fn rotate(text: &str, key: usize) -> String {\n text.chars()\n .map(|x| match x {\n _ if x.is_ascii_lowercase() => {\n let v = (x as u8 - b'a' + key as u8) % 26 + b'a';\n v as char\n }\n _ if x.is_ascii_uppercase() => {\n let v = (x as u8 - b'A' + key as u8) % 26 + b'A';\n v as char\n }\n _ => x,\n })\n .collect()\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "rustdoc: Add test for tuple rendering\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#![crate_name = \"foo\"]\n\n// @has foo/fn.tuple0.html //pre 'pub fn tuple0(x: ())'\npub fn tuple0(x: ()) -> () { x }\n// @has foo/fn.tuple1.html //pre 'pub fn tuple1(x: (i32,)) -> (i32,)'\npub fn tuple1(x: (i32,)) -> (i32,) { x }\n// @has foo/fn.tuple2.html //pre 'pub fn tuple2(x: (i32, i32)) -> (i32, i32)'\npub fn tuple2(x: (i32, i32)) -> (i32, i32) { x }\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "chore(Kernels): Add a \"mini-CLI\" for development purposes\n"
},
{
"from": "gpt",
"value": "//! Mini CLI for testing this crate at the command line without compiling the whole `stencila` binary.\n//! Run using `cargo run --all-features` in this crate (`--all-features` is needed to include optional dependencies)\n//! The `cfg` flags are just to prevent clippy complaining when running `cargo clippy` without\n//! the `--features=cli` flag.\n\n#[cfg(feature = \"cli\")]\nuse kernels::commands::Command;\n\n#[cfg(feature = \"cli\")]\ncli_utils::mini_main!(Command);\n\n#[cfg(not(feature = \"cli\"))]\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix test that was using rust_task_allow_kill incorrectly\n"
},
{
"from": "human",
"value": "/*\n A reduced test case for Issue #506, provided by Rob Arnold.\n*/\n\nuse std;\nimport task;\n\n#[abi = \"cdecl\"]\nextern mod rustrt {\n fn rust_task_allow_kill();\n}\n\nfn main() { task::spawn(rustrt::rust_task_allow_kill); }\n"
},
{
"from": "gpt",
"value": "/*\n A reduced test case for Issue #506, provided by Rob Arnold.\n\n Testing spawning foreign functions\n*/\n\nuse std;\nimport task;\n\n#[abi = \"cdecl\"]\nextern mod rustrt {\n fn unsupervise();\n}\n\nfn main() { task::spawn(rustrt::unsupervise); }\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a benchmark for the Negamax implementation.\n"
},
{
"from": "gpt",
"value": "#![feature(test)]\nextern crate minimax;\nextern crate test;\nuse test::Bencher;\nuse minimax::*;\n\n#[derive(Clone)]\npub struct Board;\n\n#[derive(Copy, Clone)]\npub struct Place;\n\npub struct Eval;\n\npub struct Noop;\n\nimpl Move for Place {\n type G = Noop;\n fn apply(&self, _: &mut Board) { }\n fn undo(&self, _: &mut Board) { }\n}\n\nimpl Game for Noop {\n type S = Board;\n type M = Place;\n\n fn generate_moves(_: &Board, _: Player, ms: &mut [Option<Place>]) -> usize {\n ms[0] = Some(Place);\n ms[1] = Some(Place);\n ms[2] = Some(Place);\n ms[3] = Some(Place);\n ms[4] = None;\n 4\n }\n\n fn get_winner(_: &Board) -> Option<Winner> { None }\n}\n\nimpl Evaluator for Eval {\n type G = Noop;\n\n fn evaluate(_: &Board, _: Option<Winner>) -> Evaluation {\n Evaluation::Score(0)\n }\n}\n\n#[bench]\nfn bench_negamax(b: &mut Bencher) {\n let board = Board;\n let mut s = Negamax::<Eval>::new(Options { max_depth: 10 });\n b.iter(|| s.choose_move(&board, Player::Computer));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for new DOM for empty impls\n"
},
{
"from": "gpt",
"value": "#![crate_name = \"foo\"]\n\n// @has foo/struct.Foo.html\n// @has - '//div[@id=\"synthetic-implementations-list\"]/h3[@id=\"impl-Send\"]' 'impl Send for Foo'\npub struct Foo;\n\npub trait EmptyTrait {}\n\n// @has - '//div[@id=\"trait-implementations-list\"]/h3[@id=\"impl-EmptyTrait\"]' 'impl EmptyTrait for Foo'\nimpl EmptyTrait for Foo {}\n\npub trait NotEmpty {\n fn foo(&self);\n}\n\n// @has - '//div[@id=\"trait-implementations-list\"]/details/summary/h3[@id=\"impl-NotEmpty\"]' 'impl NotEmpty for Foo'\nimpl NotEmpty for Foo {\n fn foo(&self) {}\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for std::any::type_name() as a const fn\n\nThis is a modified version of the test I added previously. The difference is this version implements a wrapper around std::any::type_name versus core::intrinsics::type_name, in order to show that it works as desired / intended."
},
{
"from": "gpt",
"value": "// run-pass\n\n#![feature(const_fn)]\n#![feature(const_type_name)]\n#![allow(dead_code)]\n\nconst fn type_name_wrapper<T>(_: &T) -> &'static str {\n std::any::type_name::<T>()\n}\n\nstruct Struct<TA, TB, TC> {\n a: TA,\n b: TB,\n c: TC,\n}\n\ntype StructInstantiation = Struct<i8, f64, bool>;\n\nconst CONST_STRUCT: StructInstantiation = StructInstantiation { a: 12, b: 13.7, c: false };\n\nconst CONST_STRUCT_NAME: &'static str = type_name_wrapper(&CONST_STRUCT);\n\nfn main() {\n let non_const_struct = StructInstantiation { a: 87, b: 65.99, c: true };\n\n let non_const_struct_name = type_name_wrapper(&non_const_struct);\n\n assert_eq!(CONST_STRUCT_NAME, non_const_struct_name);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for trait toggle location\n"
},
{
"from": "gpt",
"value": "#![crate_name = \"foo\"]\n\n// @has foo/trait.Foo.html\n// @has - '//details[@class=\"rustdoc-toggle\"]//code' 'bar'\npub trait Foo {\n fn bar() -> ();\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a benchmark test for edit_distance function.\n"
},
{
"from": "gpt",
"value": "#![feature(test)]\n\nextern crate test;\nextern crate bloodhound;\n\nuse test::Bencher;\nuse std::path::PathBuf;\nuse bloodhound::matching::find;\n\n#[bench]\nfn bench_edit_distance(b: &mut Bencher) {\n let haystack = vec![PathBuf::from(\"src/hound.rs\"),\n PathBuf::from(\"lib/hounds.rs\"), PathBuf::from(\"Houndfile\")];\n b.iter(|| find(\"match\", &haystack, 5));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add rust code for luhn-from case\n\nIt passed all testcases\n"
},
{
"from": "gpt",
"value": "pub struct Luhn {\n result: Option<String>,\n}\n\nfn is_valid(id: &str) -> bool {\n if id.len() < 2 {\n return false;\n }\n\n let mut index: u32 = 0;\n let mut sum: u32 = 0;\n\n for c in id.chars().rev() {\n if c.is_whitespace() {\n continue;\n }\n\n let mut v: u32;\n\n if let Some(d) = c.to_digit(10) {\n v = d;\n } else {\n return false;\n }\n\n if index % 2 != 0 {\n v *= 2;\n\n if v > 9 {\n v -= 9;\n }\n }\n\n index += 1;\n sum += v;\n }\n\n if index < 2 {\n return false;\n }\n\n (sum % 10) == 0\n}\n\nimpl<T> From<T> for Luhn\nwhere\n T: ToString,\n{\n fn from(id: T) -> Self {\n let string = id.to_string();\n\n if is_valid(&string) {\n return Luhn {\n result: Some(string),\n };\n }\n\n Luhn { result: None }\n }\n}\n\nimpl Luhn {\n pub fn is_valid(&self) -> bool {\n self.result.is_some()\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a very basic example\n"
},
{
"from": "gpt",
"value": "extern crate ansi_term;\nuse ansi_term::Colour::*;\n\nfn main() {\n println!(\"{}\", Black.paint(\"Black\"));\n println!(\"{}\", Red.paint(\"Red\"));\n println!(\"{}\", Green.paint(\"Green\"));\n println!(\"{}\", Yellow.paint(\"Yellow\"));\n println!(\"{}\", Blue.paint(\"Blue\"));\n println!(\"{}\", Purple.paint(\"Purple\"));\n println!(\"{}\", Cyan.paint(\"Cyan\"));\n println!(\"{}\", White.paint(\"White\"));\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add inline const macro test\n"
},
{
"from": "gpt",
"value": "// run-pass\n\n#![allow(incomplete_features)]\n#![feature(inline_const)]\nmacro_rules! do_const_block{\n ($val:block) => { const $val }\n}\n\nfn main() {\n let s = do_const_block!({ 22 });\n assert_eq!(s, 22);\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test to prevent regression\n"
},
{
"from": "gpt",
"value": "// check-pass\n//\n// Regression test for issue #86082\n//\n// Checks that option_env! does not panic on receiving an invalid\n// environment variable name.\n\nfn main() {\n option_env!(\"\\0=\");\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove irrelevant parts of test\n"
},
{
"from": "human",
"value": "// -*- rust -*-\n// xfail-test\n// error-pattern:Unsatisfied precondition\n\ntag list { cons(int, @list); nil; }\n\ntype bubu = {x: int, y: int};\n\npure fn less_than(x: int, y: int) -> bool { ret x < y; }\n\ntype ordered_range = {low: int, high: int} : less_than(low, high);\n\nfn main() {\n // Should fail to compile, b/c we're not doing the check\n // explicitly that a < b\n let a: int = 1;\n let b: int = 2;\n let c: ordered_range = {low: a, high: b};\n log c.low;\n}"
},
{
"from": "gpt",
"value": "// -*- rust -*-\n// xfail-test\n// error-pattern:Unsatisfied precondition\n\npure fn less_than(x: int, y: int) -> bool { ret x < y; }\n\ntype ordered_range = {low: int, high: int} : less_than(low, high);\n\nfn main() {\n // Should fail to compile, b/c we're not doing the check\n // explicitly that a < b\n let a: int = 1;\n let b: int = 2;\n let c: ordered_range = {low: a, high: b};\n log c.low;\n}"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add test for braced-macro followed by `.` or `?`.\n"
},
{
"from": "gpt",
"value": "// check-pass\n\nuse std::io::Write;\n\nfn main() -> Result<(), std::io::Error> {\n vec! { 1, 2, 3 }.len();\n write! { vec![], \"\" }?;\n Ok(())\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Test nested `proc` can access outer owned data\n\nFixes #10682\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// Regression test for issue #10682\n// Nested `proc` usage can't use outer owned data\n\nfn work(_: ~int) {}\nfn foo(_: proc()) {}\n\npub fn main() {\n let a = ~1;\n foo(proc() { foo(proc() { work(a) }) })\n}\n"
}
] | rust | chosen |
[
{
"from": "human",
"value": "Add a test for escaping LLVMisms in inline asm\n\nWe escape certain LLVM-specific features when passing the inline\nassembly string to the LLVM. Until now, however, there was no test\nmaking sure this behaviour stays intact. This commit adds such a test!\n"
},
{
"from": "gpt",
"value": "// FIXME(nagisa): remove the flags here once all targets support `asm!`.\n// compile-flags: --target x86_64-unknown-linux-gnu\n\n// Verify we sanitize the special tokens for the LLVM inline-assembly, ensuring people won't\n// inadvertently rely on the LLVM-specific syntax and features.\n#![no_core]\n#![feature(no_core, lang_items, rustc_attrs)]\n#![crate_type = \"rlib\"]\n\n#[rustc_builtin_macro]\nmacro_rules! asm {\n () => {};\n}\n\n#[lang = \"sized\"]\ntrait Sized {}\n#[lang = \"copy\"]\ntrait Copy {}\n\npub unsafe fn we_escape_dollar_signs() {\n // CHECK: call void asm sideeffect alignstack inteldialect \"banana$$:\"\n asm!(\n r\"banana$:\",\n )\n}\n\npub unsafe fn we_escape_escapes_too() {\n // CHECK: call void asm sideeffect alignstack inteldialect \"banana\\{{(\\\\|5C)}}36:\"\n asm!(\n r\"banana\\36:\",\n )\n}\n"
}
] | rust | chosen |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.