conversations
listlengths
2
3
source
stringclasses
1 value
stack
stringclasses
1 value
[ { "from": "system", "value": "Make word wrap support words longer than CHARS_PER_LINE.\n" }, { "from": "human", "value": "use std::io::{self, Write};\n\nconst CHARS_PER_LINE: usize = 78;\nconst SPACE: u8 = 32;\nconst LF: u8 = 10;\n\n// This is a *very* naive algorithm. It assumes the cursor is\n// currently at column 0, and that the string to be printed is\n// ASCII, among other things. It's good enough for our needs\n// and much more lightweight than the current crates.io\n// alternative, `textwrap`, which has a lot of dependencies.\npub fn writeln_with_wrapping(s: &str) {\n let stdout = io::stdout();\n let mut handle = stdout.lock();\n let bytes = s.as_bytes();\n let mut column = 0;\n let mut last_space = 0;\n let mut i = 0;\n\n for &c in bytes.iter() {\n i += 1;\n if c == SPACE || c == LF {\n handle.write(&bytes[last_space..i]).unwrap();\n if c == SPACE {\n column += i - last_space;\n } else {\n column = 0;\n }\n last_space = i;\n }\n if column + (i - last_space) > CHARS_PER_LINE {\n handle.write(b\"\\n\").unwrap();\n column = 0;\n }\n }\n\n handle.write(&bytes[last_space..i]).unwrap();\n handle.write(b\"\\n\").unwrap();\n}\n" }, { "from": "gpt", "value": "use std::io::{self, Write};\n\nconst CHARS_PER_LINE: usize = 78;\nconst SPACE: u8 = 32;\nconst LF: u8 = 10;\n\n// This is a *very* naive algorithm. It assumes the cursor is\n// currently at column 0, and that the string to be printed is\n// ASCII, among other things. It's good enough for our needs\n// and much more lightweight than the current crates.io\n// alternative, `textwrap`, which has a lot of dependencies.\npub fn writeln_with_wrapping(s: &str) {\n let stdout = io::stdout();\n let mut handle = stdout.lock();\n let bytes = s.as_bytes();\n let mut column = 0;\n let mut last_space = 0;\n let mut i = 0;\n\n for &c in bytes.iter() {\n i += 1;\n if c == SPACE || c == LF {\n handle.write(&bytes[last_space..i]).unwrap();\n if c == SPACE {\n column += i - last_space;\n } else {\n column = 0;\n }\n last_space = i;\n }\n if column + (i - last_space) >= CHARS_PER_LINE {\n if column == 0 {\n // Ack, we've got a really long word that exceeds the\n // length of a single line. Just write it out, breaking\n // it at the end of the line.\n handle.write(&bytes[last_space..i]).unwrap();\n last_space = i;\n }\n handle.write(b\"\\n\").unwrap();\n column = 0;\n }\n }\n\n handle.write(&bytes[last_space..i]).unwrap();\n handle.write(b\"\\n\").unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make content check accept a model name\n" }, { "from": "human", "value": "#[macro_use]\nextern crate serde_elm;\n\nuse std::env;\nuse std::fs::File;\nuse std::io::{Read, Error};\nuse std::path::Path;\n\n#[allow(dead_code)]\n#[derive(Elm)]\nstruct Simple {\n name: String\n}\n\n#[test]\nfn should_assert_elm_generation_was_done() {\n\tlet root = env::current_dir().unwrap();\n let mut path = root.clone();\n path.push(\"generated\");\n path.push(\"Simple.elm\");\n\n assert!(path.exists());\n assert!(path.is_file());\n\n let actual = contents_of(&path).unwrap();\n\n let mut expected_path = root.clone();\n expected_path.push(\"tests\");\n expected_path.push(\"assets\");\n expected_path.push(\"Simple.test.elm\");\n\n let expected = contents_of(&expected_path).unwrap();\n\n assert_eq!(actual, expected);\n}\n\nfn contents_of(path: &Path) -> Result<String, Error> {\n let mut file = File::open(path)?;\n let mut content = String::new();\n file.read_to_string(&mut content)?;\n\n Ok(content)\n}\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate serde_elm;\n\nuse std::env;\nuse std::fs::File;\nuse std::io::{Read, Error};\nuse std::path::Path;\n\n#[allow(dead_code)]\n#[derive(Elm)]\nstruct Simple {\n name: String\n}\n\n#[test]\nfn should_assert_elm_generation_was_done() {\n\tlet model_name = \"Simple\";\n\tassert!(content_equal_for(model_name))\n}\n\nfn content_equal_for<S>(model_name: S) -> bool where S: Into<String> {\n\tlet model_name = model_name.into();\n\tlet root = env::current_dir().unwrap();\n let mut path = root.clone();\n path.push(\"generated\");\n path.push(format!(\"{}.elm\", model_name));\n\n assert!(path.exists());\n assert!(path.is_file());\n\n let actual = contents_of(&path).unwrap();\n\n let mut expected_path = root.clone();\n expected_path.push(\"tests\");\n expected_path.push(\"assets\");\n expected_path.push(format!(\"{}.test.elm\", model_name));\n\n let expected = contents_of(&expected_path).unwrap();\n\n actual == expected\n}\n\nfn contents_of(path: &Path) -> Result<String, Error> {\n let mut file = File::open(path)?;\n let mut content = String::new();\n file.read_to_string(&mut content)?;\n\n Ok(content)\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make the version string a variable, at least.\n" }, { "from": "human", "value": "\n#![feature(plugin)]\n#![plugin(clippy)]\n\n#[macro_use]\nextern crate kafka;\nextern crate log;\nextern crate openssl;\nextern crate toml;\n\nmod flowgger;\n\nconst DEFAULT_CONFIG_FILE: &'static str = \"flowgger.toml\";\n\nfn main() {\n println!(\"Starting flowgger 0.1.2\");\n let config_file = std::env::args().skip(1).next().unwrap_or(DEFAULT_CONFIG_FILE.to_owned());\n flowgger::start(&config_file);\n}\n" }, { "from": "gpt", "value": "\n#![feature(plugin)]\n#![plugin(clippy)]\n\n#[macro_use]\nextern crate kafka;\nextern crate log;\nextern crate openssl;\nextern crate toml;\n\nmod flowgger;\n\nconst DEFAULT_CONFIG_FILE: &'static str = \"flowgger.toml\";\nconst FLOWGGER_VERSION_STRING: &'static str = \"0.1.2\";\n\nfn main() {\n println!(\"Flowgger v{}\", FLOWGGER_VERSION_STRING);\n let config_file = std::env::args().skip(1).next().unwrap_or(DEFAULT_CONFIG_FILE.to_owned());\n flowgger::start(&config_file);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Mark Repo.path be a PathBuf instead of a String\n\nThis is the beginning of an effort to bring in changes from the\n\"refactoring\" branch that I forgot about before publishing 0.2.0.\n" }, { "from": "human", "value": "//! Git repository representation for git-global.\n\nuse std::fmt;\n\nuse git2;\n\n/// A git repository, represented by the full path to its base directory.\n#[derive(PartialEq, Eq, Hash, Clone)]\npub struct Repo {\n path: String,\n}\n\nimpl Repo {\n pub fn new(path: String) -> Repo {\n Repo {\n path: path,\n }\n }\n\n /// Returns the full path to the repo as a `String`.\n pub fn path(&self) -> String {\n self.path.clone()\n }\n\n /// Returns the `git2::Repository` equivalent of this repo.\n pub fn as_git2_repo(&self) -> Option<git2::Repository> {\n git2::Repository::open(&self.path).ok()\n }\n}\n\nimpl fmt::Display for Repo {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.path)\n }\n}\n" }, { "from": "gpt", "value": "//! Git repository representation for git-global.\n\nuse std::fmt;\nuse std::path::PathBuf;\n\nuse git2;\n\n/// A git repository, represented by the full path to its base directory.\n#[derive(Clone, Eq, Hash, PartialEq)]\npub struct Repo {\n path: PathBuf,\n}\n\nimpl Repo {\n pub fn new(path: String) -> Repo {\n Repo {\n path: PathBuf::from(path),\n }\n }\n\n /// Returns the `git2::Repository` equivalent of this repo.\n pub fn as_git2_repo(&self) -> Option<git2::Repository> {\n git2::Repository::open(&self.path).ok()\n }\n /// Returns the full path to the repo as a `String`.\n pub fn path(&self) -> String {\n self.path.to_str().unwrap().to_string()\n }\n}\n\nimpl fmt::Display for Repo {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.path())\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unique vector matching from Problem 10\n" }, { "from": "human", "value": "enum Node<T> {\n One(T),\n Many(uint, T)\n}\n\nfn pack<T: Clone+Eq>(list: &[T]) -> ~[~[T]] {\n let mut it = list.iter();\n let mut result = ~[];\n let mut l = 1;\n loop {\n match it.nth(l - 1) {\n Some(e) => {\n let mut slice = ~[];\n slice.push(e.clone());\n for f in it.take_while(|&a| *a == *e) {\n slice.push(f.clone());\n }\n l = slice.len();\n result.push(slice);\n },\n None => break\n }\n }\n result\n}\n\nfn encode<T: Clone>(list: ~[~[T]]) -> ~[Node<T>] {\n list.map(|e|\n match *e {\n [ref a] => One(a.clone()),\n [ref a, ..] => Many(e.len(), a.clone()),\n _ => unreachable!()\n })\n}\n\n\nfn main() {\n let list =\n ~['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'];\n\n println!(\"{:?}\", encode(pack(list)));\n}\n" }, { "from": "gpt", "value": "enum Node<T> {\n One(T),\n Many(uint, T)\n}\n\nfn pack<T: Clone+Eq>(list: &[T]) -> ~[~[T]] {\n let mut it = list.iter();\n let mut result = ~[];\n let mut l = 1;\n loop {\n match it.nth(l - 1) {\n Some(e) => {\n let mut slice = ~[];\n slice.push(e.clone());\n for f in it.take_while(|&a| *a == *e) {\n slice.push(f.clone());\n }\n l = slice.len();\n result.push(slice);\n },\n None => break\n }\n }\n result\n}\n\nfn encode<T: Clone>(list: ~[~[T]]) -> ~[Node<T>] {\n list.map(|e|\n match e.len() {\n 1 => One(e[0].clone()),\n n => Many(n, e[0].clone())\n })\n}\n\n\nfn main() {\n let list =\n ~['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'];\n\n println!(\"{:?}\", encode(pack(list)));\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Return the model after training\n" }, { "from": "human", "value": "use model::Model;\n\n\npub struct Classifier {\n models: Vec<(String, Model)>\n}\n\n\nimpl Classifier {\n pub fn new() -> Classifier {\n Classifier { models: Vec::new() }\n }\n\n pub fn train(&mut self, text: &str, name: &str) {\n let model = Model::build_from_text(text);\n self.models.push((name.to_string(), model));\n }\n\n pub fn classify(&self, text: &str) -> &String {\n let model = Model::build_from_text(text);\n let &(ref name, _) = self.models\n .iter()\n .min_by_key(|&&(_, ref other_model)| model.compare(other_model))\n .unwrap();\n name\n }\n}\n" }, { "from": "gpt", "value": "use model::Model;\n\n\npub struct Classifier {\n models: Vec<(String, Model)>\n}\n\n\nimpl Classifier {\n pub fn new() -> Classifier {\n Classifier { models: Vec::new() }\n }\n\n pub fn train(&mut self, text: &str, name: &str) -> &Model {\n let model = Model::build_from_text(text);\n self.models.push((name.to_string(), model));\n\n // FIXME: is this really the best way to do this?\n &self.models.last().unwrap().1\n }\n\n pub fn classify(&self, text: &str) -> &String {\n let model = Model::build_from_text(text);\n let &(ref name, _) = self.models\n .iter()\n .min_by_key(|&&(_, ref other_model)| model.compare(other_model))\n .unwrap();\n name\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use default perl if env variable is not set.\n\nThis makes it easier to run under perlbrew that can transparently switch\nbetween perl versions.\n" }, { "from": "human", "value": "extern crate gcc;\n\nuse std::path::Path;\nuse std::process::Command;\n\nstruct Perl {\n bin: String,\n}\n\nimpl Perl {\n fn new() -> Perl {\n Perl {\n bin: std::env::var(\"PERL\").unwrap(),\n }\n }\n\n fn cfg(&self, key: &str) -> String {\n let out = Command::new(&self.bin)\n .arg(\"-MConfig\")\n .arg(\"-e\")\n .arg(format!(\"print $Config::Config{{{}}}\", key))\n .output()\n .unwrap();\n\n String::from_utf8(out.stdout).unwrap()\n }\n\n fn run(&self, script: &str) {\n let status = Command::new(&self.bin)\n .arg(script)\n .status()\n .unwrap();\n assert!(status.success());\n }\n}\n\nfn build_ouro(perl: &Perl) {\n let mut gcc = gcc::Config::new();\n\n let ccflags = perl.cfg(\"ccflags\");\n for flag in ccflags.split_whitespace() {\n gcc.flag(flag);\n }\n\n let archlib = perl.cfg(\"archlibexp\");\n let coreinc = Path::new(&archlib).join(\"CORE\");\n gcc.include(&coreinc);\n\n gcc.file(\"ouroboros/libouroboros.c\");\n gcc.compile(\"libouroboros.a\");\n}\n\nfn main() {\n let perl = Perl::new();\n\n build_ouro(&perl);\n\n perl.run(\"build/regen.pl\");\n}\n" }, { "from": "gpt", "value": "extern crate gcc;\n\nuse std::path::Path;\nuse std::process::Command;\n\nstruct Perl {\n bin: String,\n}\n\nimpl Perl {\n fn new() -> Perl {\n Perl {\n bin: std::env::var(\"PERL\").unwrap_or(\"perl\".to_owned()),\n }\n }\n\n fn cfg(&self, key: &str) -> String {\n let out = Command::new(&self.bin)\n .arg(\"-MConfig\")\n .arg(\"-e\")\n .arg(format!(\"print $Config::Config{{{}}}\", key))\n .output()\n .unwrap();\n\n String::from_utf8(out.stdout).unwrap()\n }\n\n fn run(&self, script: &str) {\n let status = Command::new(&self.bin)\n .arg(script)\n .status()\n .unwrap();\n assert!(status.success());\n }\n}\n\nfn build_ouro(perl: &Perl) {\n let mut gcc = gcc::Config::new();\n\n let ccflags = perl.cfg(\"ccflags\");\n for flag in ccflags.split_whitespace() {\n gcc.flag(flag);\n }\n\n let archlib = perl.cfg(\"archlibexp\");\n let coreinc = Path::new(&archlib).join(\"CORE\");\n gcc.include(&coreinc);\n\n gcc.file(\"ouroboros/libouroboros.c\");\n gcc.compile(\"libouroboros.a\");\n}\n\nfn main() {\n let perl = Perl::new();\n\n build_ouro(&perl);\n\n perl.run(\"build/regen.pl\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add doc comment to pass tidy check\n" }, { "from": "human", "value": "use proc_macro_srv::cli;\n\nfn main() {\n cli::run().unwrap();\n}\n" }, { "from": "gpt", "value": "//! A standalone binary for `proc-macro-srv`.\n\nuse proc_macro_srv::cli;\n\nfn main() {\n cli::run().unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use unreachable!() on debug build while unreachable::unreachable() on release build\n\n" }, { "from": "human", "value": "#[macro_use]\nextern crate log;\n\n#[cfg(unix)]\nextern crate libc;\n\nextern crate net2;\nextern crate futures;\n\n#[cfg(target_pointer_width = \"32\")]\nmacro_rules! word_len {\n () => { 4 }\n}\n\n#[cfg(target_pointer_width = \"64\")]\nmacro_rules! word_len {\n () => { 8 }\n}\n\nmacro_rules! cache_line_pad { ($N:expr) => { 64 / word_len!() - 1 - $N }}\n\n#[inline]\nfn unreachable() -> ! {\n extern crate unreachable;\n unsafe { unreachable::unreachable() }\n}\n\nuse std::fmt::Display;\nuse std::io;\n\n#[inline]\nfn other_io_err<E: Display>(e: E) -> io::Error {\n io::Error::new(io::ErrorKind::Other, e.to_string())\n}\n\npub mod slab;\npub mod buf;\npub mod nio;\npub mod reactor;\npub mod channel;\npub mod net;\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate log;\n\n#[cfg(unix)]\nextern crate libc;\n\nextern crate net2;\nextern crate futures;\n\n#[cfg(target_pointer_width = \"32\")]\nmacro_rules! word_len {\n () => { 4 }\n}\n\n#[cfg(target_pointer_width = \"64\")]\nmacro_rules! word_len {\n () => { 8 }\n}\n\nmacro_rules! cache_line_pad { ($N:expr) => { 64 / word_len!() - 1 - $N }}\n\n#[inline]\nfn unreachable() -> ! {\n if cfg!(debug_assertions) {\n unreachable!();\n } else {\n extern crate unreachable;\n unsafe { unreachable::unreachable() }\n }\n}\n\nuse std::fmt::Display;\nuse std::io;\n\n#[inline]\nfn other_io_err<E: Display>(e: E) -> io::Error {\n io::Error::new(io::ErrorKind::Other, e.to_string())\n}\n\npub mod slab;\npub mod buf;\npub mod nio;\npub mod reactor;\npub mod channel;\npub mod net;\n" } ]
rust
chosen
[ { "from": "system", "value": "Use batch_execute instead of execute\n\nIt'll should speed up the check since we'll end up with 1 round trip\ninstead of 3 and don't care about the result anyway.\n" }, { "from": "human", "value": "extern crate r2d2;\nextern crate postgres;\n\nuse postgres::{PostgresConnection, PostgresConnectParams, IntoConnectParams, SslMode};\nuse postgres::error::PostgresConnectError;\n\npub struct PostgresPoolManager {\n params: PostgresConnectParams,\n ssl_mode: SslMode,\n}\n\nimpl PostgresPoolManager {\n pub fn new<T: IntoConnectParams>(params: T, ssl_mode: SslMode)\n -> Result<PostgresPoolManager, PostgresConnectError> {\n Ok(PostgresPoolManager {\n params: try!(params.into_connect_params()),\n ssl_mode: ssl_mode,\n })\n }\n}\n\nimpl r2d2::PoolManager<PostgresConnection, PostgresConnectError> for PostgresPoolManager {\n fn connect(&self) -> Result<PostgresConnection, PostgresConnectError> {\n PostgresConnection::connect(self.params.clone(), &self.ssl_mode)\n }\n\n fn is_valid(&self, conn: &PostgresConnection) -> bool {\n conn.execute(\"SELECT 1\", []).is_ok()\n }\n}\n" }, { "from": "gpt", "value": "extern crate r2d2;\nextern crate postgres;\n\nuse postgres::{PostgresConnection, PostgresConnectParams, IntoConnectParams, SslMode};\nuse postgres::error::PostgresConnectError;\n\npub struct PostgresPoolManager {\n params: PostgresConnectParams,\n ssl_mode: SslMode,\n}\n\nimpl PostgresPoolManager {\n pub fn new<T: IntoConnectParams>(params: T, ssl_mode: SslMode)\n -> Result<PostgresPoolManager, PostgresConnectError> {\n Ok(PostgresPoolManager {\n params: try!(params.into_connect_params()),\n ssl_mode: ssl_mode,\n })\n }\n}\n\nimpl r2d2::PoolManager<PostgresConnection, PostgresConnectError> for PostgresPoolManager {\n fn connect(&self) -> Result<PostgresConnection, PostgresConnectError> {\n PostgresConnection::connect(self.params.clone(), &self.ssl_mode)\n }\n\n fn is_valid(&self, conn: &PostgresConnection) -> bool {\n conn.batch_execute(\"SELECT 1\").is_ok()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unnecessary import and function definition\n" }, { "from": "human", "value": "// This file was generated automatically by crowbook-localize.\n// It is probably not a good idea to edit it manually.\n//\n// # Usage:\n//\n// ```rust, no_run\n// extern crate crowbook_intl_runtime;\n// #[macro_use] mod localize_macros;\n// crowbook_intl_runtime::set_lang(\"en\");\n// lformat!(\"Hello, {}\", name);\n// set_lang(\"fr\");\n// lformat!(\"Hello, {}\", name);\n// ```\n\nuse crowbook_intl_runtime;\n\nuse std::sync::RwLockReadGuard;\n\n#[doc(hidden)]\npub fn __get_lang() -> RwLockReadGuard<'static, String> {\n crowbook_intl_runtime::__get_lang()\n}\n\n\n" }, { "from": "gpt", "value": "// This file was generated automatically by crowbook-localize.\n// It is probably not a good idea to edit it manually.\n//\n// # Usage:\n//\n// ```rust, no_run\n// extern crate crowbook_intl_runtime;\n// #[macro_use] mod localize_macros;\n// crowbook_intl_runtime::set_lang(\"en\");\n// lformat!(\"Hello, {}\", name);\n// set_lang(\"fr\");\n// lformat!(\"Hello, {}\", name);\n// ```\n\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a second test case\n" }, { "from": "human", "value": "// test4.rs\n// This test covers the sections:\n// - Modules\n// - Macros\n\n// Write a macro that passes the test! No hints this time, you can do it!\n\n// I AM NOT DONE\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_my_macro() {\n assert_eq!(my_macro!(\"world!\"), \"Hello world!\");\n }\n}\n\n" }, { "from": "gpt", "value": "// test4.rs\n// This test covers the sections:\n// - Modules\n// - Macros\n\n// Write a macro that passes the test! No hints this time, you can do it!\n\n// I AM NOT DONE\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_my_macro_world() {\n assert_eq!(my_macro!(\"world!\"), \"Hello world!\");\n }\n\n #[test]\n fn test_my_macro_goodbye() {\n assert_eq!(my_macro!(\"goodbye!\"), \"Hello goodbye!\");\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a `<<` operator on `Write`ers like on C++ IOStream\n" }, { "from": "human", "value": "//\n// SOS: the Stupid Operating System\n// by Hawk Weisman (hi@hawkweisman.me)\n//\n// Copyright (c) 2015 Hawk Weisman\n// Released under the terms of the MIT license. See `LICENSE` in the root\n// directory of this repository for more information.\n//\npub mod term;\n\n/// This is basically a braindead reimplementation of the standard\n/// library's `Read` trait. Most of the methods available on the\n/// standard lib's `Read` are not yet implemented.\npub trait Read {\n type Error;\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;\n fn read_all(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;\n}\n\npub trait Write {\n type Error;\n fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error>;\n}\n" }, { "from": "gpt", "value": "//\n// SOS: the Stupid Operating System\n// by Hawk Weisman (hi@hawkweisman.me)\n//\n// Copyright (c) 2015 Hawk Weisman\n// Released under the terms of the MIT license. See `LICENSE` in the root\n// directory of this repository for more information.\n//\npub mod term;\nuse core::ops;\n\n/// This is basically a braindead reimplementation of the standard\n/// library's `Read` trait. Most of the methods available on the\n/// standard lib's `Read` are not yet implemented.\npub trait Read {\n type Error;\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;\n fn read_all(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error>;\n}\n\npub trait Write {\n type Error;\n fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error>;\n}\n\nimpl<'a, 'b, E> ops::Shl<&'a [u8]> for &'b mut Write<Error=E> {\n type Output = Self;\n\n /// Fakes the C++ `<<` operator for IOStreams on Write.\n fn shl(self, _rhs: &'a [u8]) -> Self::Output {\n try!(self.write(_rhs));\n self\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make a comment on a test less sensational.\n" }, { "from": "human", "value": "// It's OK to destroy a heap when some GcRefs still exist. (!)\n//\n// Rust's safety rules ensure that the GcRefs won't still be accessible\n// afterwards, so if this happens, it means the values were leaked.\n\nextern crate cell_gc;\n\nuse cell_gc::Heap;\nuse std::mem;\nuse std::sync::Arc;\n\n#[test]\nfn test_leaked_ref() {\n let counted = Arc::new(false);\n assert_eq!(Arc::strong_count(&counted), 1);\n\n let mut heap = Heap::new();\n heap.enter(|hs| {\n let a = hs.alloc(counted.clone());\n assert_eq!(Arc::strong_count(&counted), 2);\n mem::forget(a);\n\n // The Arc in the heap remains pinned.\n hs.force_gc();\n assert_eq!(Arc::strong_count(&counted), 2);\n });\n\n // This destroys all remaining in-heap values, even though we leaked a\n // strong reference.\n drop(heap);\n\n assert_eq!(Arc::strong_count(&counted), 1);\n}\n" }, { "from": "gpt", "value": "// It's OK to destroy a heap when some GcRefs have not been dropped. (!)\n//\n// Rust's safety rules ensure that the GcRefs won't still be accessible\n// afterwards, so if this happens, it means the values were leaked.\n\nextern crate cell_gc;\n\nuse cell_gc::Heap;\nuse std::mem;\nuse std::sync::Arc;\n\n#[test]\nfn test_leaked_ref() {\n let counted = Arc::new(false);\n assert_eq!(Arc::strong_count(&counted), 1);\n\n let mut heap = Heap::new();\n heap.enter(|hs| {\n let a = hs.alloc(counted.clone());\n assert_eq!(Arc::strong_count(&counted), 2);\n mem::forget(a);\n\n // The Arc in the heap remains pinned.\n hs.force_gc();\n assert_eq!(Arc::strong_count(&counted), 2);\n });\n\n // This destroys all remaining in-heap values, even though we leaked a\n // strong reference.\n drop(heap);\n\n assert_eq!(Arc::strong_count(&counted), 1);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use ProcessAction in Windows handler for clippy\n" }, { "from": "human", "value": "use anyhow::{bail, Result};\nuse std::process::{Child, Command};\n\nuse crate::task_handler::ProcessAction;\nuse log::info;\n\npub fn compile_shell_command(command_string: &str) -> Command {\n // Chain two `powershell` commands, one that sets the output encoding to utf8 and then the user provided one.\n let mut command = Command::new(\"powershell\");\n command.arg(\"-c\").arg(format!(\n \"[Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8; {}\",\n command_string\n ));\n\n command\n}\n\n/// Send a signal to a windows process.\npub fn send_signal_to_child(\n _child: &Child,\n _action: &ProcessAction,\n _children: bool,\n) -> Result<bool> {\n bail!(\"not supported on windows.\")\n}\n\n/// Kill a child process\npub fn kill_child(task_id: usize, child: &mut Child, _kill_children: bool) -> bool {\n match child.kill() {\n Err(_) => {\n info!(\"Task {} has already finished by itself\", task_id);\n false\n }\n Ok(_) => true,\n }\n}\n" }, { "from": "gpt", "value": "use anyhow::{bail, Result};\nuse std::process::{Child, Command};\n\nuse crate::task_handler::ProcessAction;\nuse log::info;\n\npub fn compile_shell_command(command_string: &str) -> Command {\n // Chain two `powershell` commands, one that sets the output encoding to utf8 and then the user provided one.\n let mut command = Command::new(\"powershell\");\n command.arg(\"-c\").arg(format!(\n \"[Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8; {}\",\n command_string\n ));\n\n command\n}\n\n/// Send a signal to a windows process.\npub fn send_signal_to_child(\n _child: &Child,\n action: &ProcessAction,\n _children: bool,\n) -> Result<bool> {\n match action {\n ProcessAction::Pause => bail!(\"Pause is not yet supported on windows.\"),\n ProcessAction::Resume => bail!(\"Resume is not yet supported on windows.\"),\n ProcessAction::Kill => bail!(\"Kill is not yet supported on windows.\"),\n }\n}\n\n/// Kill a child process\npub fn kill_child(task_id: usize, child: &mut Child, _kill_children: bool) -> bool {\n match child.kill() {\n Err(_) => {\n info!(\"Task {} has already finished by itself\", task_id);\n false\n }\n Ok(_) => true,\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix tests of utility `wpublisher`, use compile mode directives\n" }, { "from": "human", "value": "\nuse super::*;\n\n//\n\ntests_impls!\n{\n fn basic_no_args()\n {\n let path = std::ffi::OsStr::new( \"../../../target/debug/wpublisher\" );\n let proc = std::process::Command::new( path ).output().unwrap();\n assert!( !proc.status.success() );\n let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();\n assert_eq!( stderr, \"Ambiguity. Did you mean?\\n\" );\n let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();\n assert!( stdout.contains( \".list - List packages.\" ) );\n }\n\n //\n\n fn basic_with_args()\n {\n let path = std::ffi::OsStr::new( \"../../../target/debug/wpublisher\" );\n let proc = std::process::Command::new( path ).arg( \".list\" ).output().unwrap();\n assert!( proc.status.success() );\n let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();\n assert_eq!( stdout, \"\" );\n let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();\n assert_eq!( stderr, \"\" );\n }\n}\n\n//\n\ntests_index!\n{\n basic_no_args,\n basic_with_args,\n}\n" }, { "from": "gpt", "value": "\nuse super::*;\n\n//\n\ntests_impls!\n{\n fn basic_no_args()\n {\n #[ cfg( debug_assertions ) ]\n let path = std::ffi::OsStr::new( \"../../../target/debug/wpublisher\" );\n #[ cfg( not( debug_assertions ) ) ]\n let path = std::ffi::OsStr::new( \"../../../target/release/wpublisher\" );\n let proc = std::process::Command::new( path ).output().unwrap();\n assert!( !proc.status.success() );\n let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();\n assert_eq!( stderr, \"Ambiguity. Did you mean?\\n\" );\n let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();\n assert!( stdout.contains( \".list - List packages.\" ) );\n }\n\n //\n\n fn basic_with_args()\n {\n #[ cfg( debug_assertions ) ]\n let path = std::ffi::OsStr::new( \"../../../target/debug/wpublisher\" );\n #[ cfg( not( debug_assertions ) ) ]\n let path = std::ffi::OsStr::new( \"../../../target/release/wpublisher\" );\n let proc = std::process::Command::new( path ).arg( \".list\" ).output().unwrap();\n assert!( proc.status.success() );\n let stdout = std::str::from_utf8( proc.stdout.as_slice() ).unwrap();\n assert_eq!( stdout, \"\" );\n let stderr = std::str::from_utf8( proc.stderr.as_slice() ).unwrap();\n assert_eq!( stderr, \"\" );\n }\n}\n\n//\n\ntests_index!\n{\n basic_no_args,\n basic_with_args,\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use intradoc-links for the whole test, add a @has check\n\nCo-authored-by: Joshua Nelson <d6955d9721560531274cb8f50ff595a9bd39d66f@yottadb.com>" }, { "from": "human", "value": "// ignore-tidy-linelength\n\npub mod internal {\n pub struct r#mod;\n\n /// See [name], [other name]\n ///\n /// [name]: mod\n /// [other name]: ../internal/struct.mod.html\n // @has 'raw_ident_eliminate_r_hashtag/internal/struct.B.html' '//a[@href=\"../raw_ident_eliminate_r_hashtag/internal/struct.mod.html\"]' 'name'\n // @has 'raw_ident_eliminate_r_hashtag/internal/struct.B.html' '//a[@href=\"../raw_ident_eliminate_r_hashtag/internal/struct.mod.html\"]' 'other name'\n pub struct B;\n}\n\n/// See [name].\n///\n/// [name]: internal::mod\n// @has 'raw_ident_eliminate_r_hashtag/struct.A.html' '//a[@href=\"../raw_ident_eliminate_r_hashtag/internal/struct.mod.html\"]' 'name'\nstruct A;\n" }, { "from": "gpt", "value": "// ignore-tidy-linelength\n\npub mod internal {\n // @has 'raw_ident_eliminate_r_hashtag/internal/struct.mod.html'\n pub struct r#mod;\n\n /// See [name], [other name]\n ///\n /// [name]: mod\n /// [other name]: crate::internal::mod\n // @has 'raw_ident_eliminate_r_hashtag/internal/struct.B.html' '//a[@href=\"../raw_ident_eliminate_r_hashtag/internal/struct.mod.html\"]' 'name'\n // @has 'raw_ident_eliminate_r_hashtag/internal/struct.B.html' '//a[@href=\"../raw_ident_eliminate_r_hashtag/internal/struct.mod.html\"]' 'other name'\n pub struct B;\n}\n\n/// See [name].\n///\n/// [name]: internal::mod\n// @has 'raw_ident_eliminate_r_hashtag/struct.A.html' '//a[@href=\"../raw_ident_eliminate_r_hashtag/internal/struct.mod.html\"]' 'name'\nstruct A;\n" } ]
rust
chosen
[ { "from": "system", "value": "Convert try! to ? operator.\n" }, { "from": "human", "value": "use std::env;\nuse std::fs::{copy, create_dir_all, read_dir};\nuse std::path::{Path, PathBuf};\nuse std::io;\n\nfn main() {\n let res_dir_source = Path::new(&env::var(\"CARGO_MANIFEST_DIR\").unwrap()).join(\"resources/\");\n let res_dir_target = Path::new(&env::var(\"OUT_DIR\").unwrap()).join(\"../../../resources/\");\n\n //copies all resource files to \"target/NAME/resources\". Prints out any errors if failed.\n if let Err(io_error) = add_resources(&res_dir_source, &res_dir_target) {\n println!(\"OS Error: {}\", io_error);\n }\n}\n\n///Recursively copy all files in dir given by source_path to dir given by target path\n///WARNING! Overwrites files with same name\nfn add_resources(source_path: &PathBuf, target_path: &PathBuf) -> io::Result<()> {\n match read_dir(source_path) {\n Ok(entry_iter) => {\n try!(create_dir_all(target_path));\n for entry in entry_iter {\n let entry = try!(entry);\n let source_path = entry.path();\n let target_path = target_path.join(entry.file_name());\n try!(add_resources(&source_path, &target_path));\n }\n }\n Err(_) => {\n try!(copy(&source_path, &target_path));\n }\n }\n Ok(())\n}\n" }, { "from": "gpt", "value": "use std::env;\nuse std::fs::{copy, create_dir_all, read_dir};\nuse std::path::{Path, PathBuf};\nuse std::io;\n\nfn main() {\n let res_dir_source = Path::new(&env::var(\"CARGO_MANIFEST_DIR\").unwrap()).join(\"resources/\");\n let res_dir_target = Path::new(&env::var(\"OUT_DIR\").unwrap()).join(\"../../../resources/\");\n\n //copies all resource files to \"target/NAME/resources\". Prints out any errors if failed.\n if let Err(io_error) = add_resources(&res_dir_source, &res_dir_target) {\n println!(\"OS Error: {}\", io_error);\n }\n}\n\n///Recursively copy all files in dir given by source_path to dir given by target path\n///WARNING! Overwrites files with same name\nfn add_resources(source_path: &PathBuf, target_path: &PathBuf) -> io::Result<()> {\n match read_dir(source_path) {\n Ok(entry_iter) => {\n create_dir_all(target_path)?;\n for entry in entry_iter {\n let entry = entry?;\n let source_path = entry.path();\n let target_path = target_path.join(entry.file_name());\n add_resources(&source_path, &target_path)?;\n }\n }\n Err(_) => {\n copy(&source_path, &target_path)?;\n }\n }\n Ok(())\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Upgrade to rustc 1.0.0-dev (47551b574 2015-04-14) (built 2015-03-18)\n" }, { "from": "human", "value": "/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\n#![feature(io, os)]\n\nuse std::old_io::process::{Command, ProcessExit, StdioContainer};\nuse std::os;\n\n\nfn main() {\n let out_dir = os::getenv(\"OUT_DIR\").unwrap();\n let result = Command::new(\"make\")\n .args(&[\"-f\", \"makefile.cargo\", \"-j4\"])\n .stdout(StdioContainer::InheritFd(1))\n .stderr(StdioContainer::InheritFd(2))\n .status()\n .unwrap();\n assert_eq!(result, ProcessExit::ExitStatus(0));\n println!(\"cargo:rustc-flags=-L native={}\", out_dir);\n}\n" }, { "from": "gpt", "value": "/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse std::process::Command;\nuse std::env;\n\n\nfn main() {\n assert!(Command::new(\"make\")\n .args(&[\"-f\", \"makefile.cargo\", \"-j4\"])\n .status()\n .unwrap()\n .success());\n println!(\"cargo:rustc-flags=-L native={}\", env::var(\"OUT_DIR\").unwrap());\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add conversion to/from io::Error for kv::Error\n\nAnd keep the original error, so that an io error inside the visitor is\nreturned accessible by the call to `visit`.\n" }, { "from": "human", "value": "use std::fmt;\n\n/// An error encountered while working with structured data.\n#[derive(Clone, Debug)]\npub struct Error {\n msg: &'static str,\n}\n\nimpl Error {\n /// Create an error from the given message.\n pub fn msg(msg: &'static str) -> Self {\n Error {\n msg: msg,\n }\n }\n}\n\nimpl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n self.msg.fmt(f)\n }\n}\n\nimpl From<fmt::Error> for Error {\n fn from(_: fmt::Error) -> Self {\n Error::msg(\"formatting failed\")\n }\n}\n\nimpl From<Error> for fmt::Error {\n fn from(_: Error) -> Self {\n fmt::Error\n }\n}\n\n#[cfg(feature = \"std\")]\nmod std_support {\n use super::*;\n use std::error;\n\n impl error::Error for Error {\n fn description(&self) -> &str {\n \"key values error\"\n }\n }\n}\n" }, { "from": "gpt", "value": "use std::fmt;\n\n/// An error encountered while working with structured data.\n#[derive(Debug)]\npub struct Error {\n inner: Inner\n}\n\n#[derive(Debug)]\nenum Inner {\n #[cfg(feature = \"std\")]\n Io(std::io::Error),\n Msg(&'static str),\n Fmt,\n}\n\nimpl Error {\n /// Create an error from the given message.\n pub fn msg(msg: &'static str) -> Self {\n Error {\n inner: Inner::Msg(msg),\n }\n }\n}\n\nimpl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n use self::Inner::*;\n match &self.inner {\n #[cfg(feature = \"std\")]\n Io(err) => err.fmt(f),\n Msg(msg) => msg.fmt(f),\n Fmt => fmt::Error.fmt(f),\n }\n }\n}\n\nimpl From<fmt::Error> for Error {\n fn from(_: fmt::Error) -> Self {\n Error {\n inner: Inner::Fmt,\n }\n }\n}\n\nimpl From<Error> for fmt::Error {\n fn from(_: Error) -> Self {\n fmt::Error\n }\n}\n\n#[cfg(feature = \"std\")]\nmod std_support {\n use super::*;\n use std::{error, io};\n\n impl error::Error for Error {\n fn description(&self) -> &str {\n \"key values error\"\n }\n }\n\n impl From<io::Error> for Error {\n fn from(err: io::Error) -> Self {\n Error {\n inner: Inner::Io(err)\n }\n }\n }\n\n impl From<Error> for io::Error {\n fn from(err: Error) -> Self {\n if let Inner::Io(err) = err.inner {\n err\n } else {\n io::Error::new(io::ErrorKind::Other, err)\n }\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Increase worker thread stack and name them\n" }, { "from": "human", "value": "//! A thin wrapper around `ThreadPool` to make sure that we join all things\n//! properly.\nuse crossbeam_channel::Sender;\n\npub(crate) struct TaskPool<T> {\n sender: Sender<T>,\n inner: threadpool::ThreadPool,\n}\n\nimpl<T> TaskPool<T> {\n pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {\n TaskPool { sender, inner: threadpool::ThreadPool::default() }\n }\n\n pub(crate) fn spawn<F>(&mut self, task: F)\n where\n F: FnOnce() -> T + Send + 'static,\n T: Send + 'static,\n {\n self.inner.execute({\n let sender = self.sender.clone();\n move || sender.send(task()).unwrap()\n })\n }\n\n pub(crate) fn spawn_with_sender<F>(&mut self, task: F)\n where\n F: FnOnce(Sender<T>) + Send + 'static,\n T: Send + 'static,\n {\n self.inner.execute({\n let sender = self.sender.clone();\n move || task(sender)\n })\n }\n\n pub(crate) fn len(&self) -> usize {\n self.inner.queued_count()\n }\n}\n\nimpl<T> Drop for TaskPool<T> {\n fn drop(&mut self) {\n self.inner.join()\n }\n}\n" }, { "from": "gpt", "value": "//! A thin wrapper around `ThreadPool` to make sure that we join all things\n//! properly.\nuse crossbeam_channel::Sender;\n\npub(crate) struct TaskPool<T> {\n sender: Sender<T>,\n inner: threadpool::ThreadPool,\n}\n\nimpl<T> TaskPool<T> {\n pub(crate) fn new(sender: Sender<T>) -> TaskPool<T> {\n const STACK_SIZE: usize = 8 * 1024 * 1024;\n\n let inner = threadpool::Builder::new()\n .thread_name(\"Worker\".into())\n .thread_stack_size(STACK_SIZE)\n .build();\n TaskPool { sender, inner }\n }\n\n pub(crate) fn spawn<F>(&mut self, task: F)\n where\n F: FnOnce() -> T + Send + 'static,\n T: Send + 'static,\n {\n self.inner.execute({\n let sender = self.sender.clone();\n move || sender.send(task()).unwrap()\n })\n }\n\n pub(crate) fn spawn_with_sender<F>(&mut self, task: F)\n where\n F: FnOnce(Sender<T>) + Send + 'static,\n T: Send + 'static,\n {\n self.inner.execute({\n let sender = self.sender.clone();\n move || task(sender)\n })\n }\n\n pub(crate) fn len(&self) -> usize {\n self.inner.queued_count()\n }\n}\n\nimpl<T> Drop for TaskPool<T> {\n fn drop(&mut self) {\n self.inner.join()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove obsolete fixed-length string test\n" }, { "from": "human", "value": "fn wants_box(x: @str) { }\nfn wants_uniq(x: ~str) { }\nfn wants_three(x: str/3) { }\n\nfn has_box(x: @str) {\n wants_box(x);\n wants_uniq(x); //~ ERROR str storage differs: expected ~ but found @\n wants_three(x); //~ ERROR str storage differs: expected 3 but found @\n}\n\nfn has_uniq(x: ~str) {\n wants_box(x); //~ ERROR str storage differs: expected @ but found ~\n wants_uniq(x);\n wants_three(x); //~ ERROR str storage differs: expected 3 but found ~\n}\n\nfn has_three(x: str/3) {\n wants_box(x); //~ ERROR str storage differs: expected @ but found 3\n wants_uniq(x); //~ ERROR str storage differs: expected ~ but found 3\n wants_three(x);\n}\n\nfn has_four(x: str/4) {\n wants_box(x); //~ ERROR str storage differs: expected @ but found 4\n wants_uniq(x); //~ ERROR str storage differs: expected ~ but found 4\n wants_three(x); //~ ERROR str storage differs: expected 3 but found 4\n}\n\nfn main() {\n}\n" }, { "from": "gpt", "value": "fn wants_box(x: @str) { }\nfn wants_uniq(x: ~str) { }\nfn wants_slice(x: &str) { }\n\nfn has_box(x: @str) {\n wants_box(x);\n wants_uniq(x); //~ ERROR str storage differs: expected ~ but found @\n wants_slice(x);\n}\n\nfn has_uniq(x: ~str) {\n wants_box(x); //~ ERROR str storage differs: expected @ but found ~\n wants_uniq(x);\n wants_slice(x);\n}\n\nfn has_slice(x: &str) {\n wants_box(x); //~ ERROR str storage differs: expected @ but found &\n wants_uniq(x); //~ ERROR str storage differs: expected ~ but found &\n wants_slice(x);\n}\n\nfn main() {\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove remaining uses of old fixed-length vec syntax\n" }, { "from": "human", "value": "// Issue #3656\n// Incorrect struct size computation in the FFI, because of not taking\n// the alignment of elements into account.\n\nuse libc::*;\n\nstruct KEYGEN {\n hash_algorithm: [c_uint]/2,\n count: uint32_t,\n salt: *c_void,\n salt_size: uint32_t,\n}\n\nextern {\n // Bogus signature, just need to test if it compiles.\n pub fn malloc(++data: KEYGEN);\n}\n\nfn main() {\n}\n" }, { "from": "gpt", "value": "// Issue #3656\n// Incorrect struct size computation in the FFI, because of not taking\n// the alignment of elements into account.\n\nuse libc::*;\n\nstruct KEYGEN {\n hash_algorithm: [c_uint * 2],\n count: uint32_t,\n salt: *c_void,\n salt_size: uint32_t,\n}\n\nextern {\n // Bogus signature, just need to test if it compiles.\n pub fn malloc(++data: KEYGEN);\n}\n\nfn main() {\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use to_owned instead of to_string\n\nIt’s always faster\n" }, { "from": "human", "value": "use model::Model;\n\n\npub struct Classifier {\n models: Vec<(String, Model)>\n}\n\n\nimpl Classifier {\n pub fn new() -> Classifier {\n Classifier { models: Vec::new() }\n }\n\n pub fn train(&mut self, text: &str, name: &str) {\n let model = Model::build_from_text(text);\n self.models.push((name.to_string(), model));\n }\n\n pub fn classify(&self, text: &str) -> &String {\n let model = Model::build_from_text(text);\n let &(ref name, _) = self.models\n .iter()\n .min_by_key(|&&(_, ref other_model)| model.compare(other_model))\n .unwrap();\n name\n }\n}\n" }, { "from": "gpt", "value": "use model::Model;\n\n\npub struct Classifier {\n models: Vec<(String, Model)>\n}\n\n\nimpl Classifier {\n pub fn new() -> Classifier {\n Classifier { models: Vec::new() }\n }\n\n pub fn train(&mut self, text: &str, name: &str) {\n let model = Model::build_from_text(text);\n self.models.push((name.to_owned(), model));\n }\n\n pub fn classify(&self, text: &str) -> &String {\n let model = Model::build_from_text(text);\n let &(ref name, _) = self.models\n .iter()\n .min_by_key(|&&(_, ref other_model)| model.compare(other_model))\n .unwrap();\n name\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Implement `Changeset` for `Vec<T>` and `Box<T>`\n\nA valid use case has arisen in #26 that is impossible to work around at\nthe moment. We're going to eventually add a standard API to handle this,\nso this implementation has no tests. It will get tested through that\nAPI, once we've figured out what the API will look like. But I want to\nget this through so it's possible to work around this by implementing\n`AsChangeset` manually.\n" }, { "from": "human", "value": "use query_builder::{QueryBuilder, BuildQueryResult};\nuse query_source::QuerySource;\n\npub trait AsChangeset {\n type Changeset: Changeset;\n\n fn as_changeset(self) -> Self::Changeset;\n}\n\npub trait Changeset {\n type Target: QuerySource;\n\n fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult;\n}\n\nimpl<T> AsChangeset for T where\n T: Changeset,\n{\n type Changeset = Self;\n\n fn as_changeset(self) -> Self::Changeset {\n self\n }\n}\n" }, { "from": "gpt", "value": "use query_builder::{QueryBuilder, BuildQueryResult};\nuse query_source::QuerySource;\n\npub trait AsChangeset {\n type Changeset: Changeset;\n\n fn as_changeset(self) -> Self::Changeset;\n}\n\npub trait Changeset {\n type Target: QuerySource;\n\n fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult;\n}\n\nimpl<T> AsChangeset for T where\n T: Changeset,\n{\n type Changeset = Self;\n\n fn as_changeset(self) -> Self::Changeset {\n self\n }\n}\n\nimpl<T: Changeset> Changeset for Vec<T> {\n type Target = T::Target;\n\n fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult {\n for (i, changeset) in self.iter().enumerate() {\n if i != 0 {\n out.push_sql(\", \");\n }\n try!(changeset.to_sql(out))\n }\n Ok(())\n }\n}\n\nimpl<T: Changeset> Changeset for Box<T> {\n type Target = T::Target;\n\n fn to_sql(&self, out: &mut QueryBuilder) -> BuildQueryResult {\n (&**self).to_sql(out)\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add Sized trait to ElementType\n" }, { "from": "human", "value": "#![feature(zero_one, box_syntax)]\n\nextern crate asexp;\n\npub mod num_expr;\npub mod cond;\n\nuse std::fmt::Debug;\nuse std::cmp::{PartialEq, PartialOrd};\n\n#[derive(Debug, Eq, PartialEq)]\npub enum ExpressionError {\n /// In case of division by zero.\n DivByZero,\n /// In case an invalid variable in references from the expression.\n InvalidVariable,\n /// In case of an invalid operation.\n InvalidOperation,\n}\n\npub trait ElementType: Debug + Copy + Clone + PartialEq + PartialOrd + Default {}\n\npub trait Expression: Debug + Clone + PartialEq\n{\n type Element: ElementType;\n /// Evaluates the expression with the given variables bound.\n fn evaluate(&self, variables: &[Self::Element]) -> Result<Self::Element, ExpressionError>;\n\n /// Constructs a constant expression. Required by lindenmayer-system.\n fn make_const(elm: Self::Element) -> Self;\n}\n\npub trait Condition: Debug + Clone + PartialEq\n{\n type Expr: Expression;\n /// Evaluate the condition with the given variables bound.\n fn evaluate(&self,\n variables: &[<Self::Expr as Expression>::Element])\n -> Result<bool, ExpressionError>;\n}\n" }, { "from": "gpt", "value": "#![feature(zero_one, box_syntax)]\n\nextern crate asexp;\n\npub mod num_expr;\npub mod cond;\n\nuse std::fmt::Debug;\nuse std::cmp::{PartialEq, PartialOrd};\n\n#[derive(Debug, Eq, PartialEq)]\npub enum ExpressionError {\n /// In case of division by zero.\n DivByZero,\n /// In case an invalid variable in references from the expression.\n InvalidVariable,\n /// In case of an invalid operation.\n InvalidOperation,\n}\n\npub trait ElementType: Debug + Copy + Clone + PartialEq + PartialOrd + Default + Sized {}\n\npub trait Expression: Debug + Clone + PartialEq\n{\n type Element: ElementType;\n /// Evaluates the expression with the given variables bound.\n fn evaluate(&self, variables: &[Self::Element]) -> Result<Self::Element, ExpressionError>;\n\n /// Constructs a constant expression. Required by lindenmayer-system.\n fn make_const(elm: Self::Element) -> Self;\n}\n\npub trait Condition: Debug + Clone + PartialEq\n{\n type Expr: Expression;\n /// Evaluate the condition with the given variables bound.\n fn evaluate(&self,\n variables: &[<Self::Expr as Expression>::Element])\n -> Result<bool, ExpressionError>;\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add GitHub link within the documentation\n" }, { "from": "human", "value": "//! An implementation of [FLAC](https://xiph.org/flac), free lossless audio\n//! codec, written in Rust.\n//!\n//! # Examples\n//!\n//! Basic decoding from a file.\n//!\n//! ```\n//! use flac::{Stream, ReadStream};\n//! use std::fs::File;\n//!\n//! match Stream::<ReadStream<File>>::from_file(\"path/to/file.flac\") {\n//! Ok(mut stream) => {\n//! // Copy of `StreamInfo` to help convert to a different audio format.\n//! let info = stream.info();\n//!\n//! for sample in stream.iter() {\n//! // Iterate over each decoded sample\n//! }\n//! }\n//! Err(error) => println!(\"{}\", error),\n//! }\n//! ```\n\n#[macro_use]\nextern crate nom;\n\n#[macro_use]\nmod utility;\nmod frame;\nmod subframe;\npub mod metadata;\npub mod stream;\n\npub use metadata::Metadata;\npub use stream::Stream;\npub use utility::{StreamProducer, ReadStream, ByteStream};\n" }, { "from": "gpt", "value": "//! An implementation of [FLAC](https://xiph.org/flac), free lossless audio\n//! codec, written in Rust.\n//!\n//! The code is available on [GitHub](https://github.com/sourrust/flac).\n//!\n//! # Examples\n//!\n//! Basic decoding from a file.\n//!\n//! ```\n//! use flac::{Stream, ReadStream};\n//! use std::fs::File;\n//!\n//! match Stream::<ReadStream<File>>::from_file(\"path/to/file.flac\") {\n//! Ok(mut stream) => {\n//! // Copy of `StreamInfo` to help convert to a different audio format.\n//! let info = stream.info();\n//!\n//! for sample in stream.iter() {\n//! // Iterate over each decoded sample\n//! }\n//! }\n//! Err(error) => println!(\"{}\", error),\n//! }\n//! ```\n\n#[macro_use]\nextern crate nom;\n\n#[macro_use]\nmod utility;\nmod frame;\nmod subframe;\npub mod metadata;\npub mod stream;\n\npub use metadata::Metadata;\npub use stream::Stream;\npub use utility::{StreamProducer, ReadStream, ByteStream};\n" } ]
rust
chosen
[ { "from": "system", "value": "Add `ignore-tidy-linelength` and fix formatting\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\nuse std::ops::{Add, Sub};\n\ntype Test = Add +\n //~^ ERROR the type parameter `RHS` must be explicitly specified in an object type because its default value `Self` references the type `Self`\n Sub;\n //~^ ERROR only the builtin traits can be used as closure or object bounds\n\nfn main() {\n}\n" }, { "from": "gpt", "value": "// Copyright 2015 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// ignore-tidy-linelength\n\nuse std::ops::{Add, Sub};\n\ntype Test = Add +\n //~^ ERROR the type parameter `RHS` must be explicitly specified in an object type because its default value `Self` references the type `Self`\n Sub;\n //~^ ERROR only the builtin traits can be used as closure or object bounds\n\nfn main() { }\n" } ]
rust
chosen
[ { "from": "system", "value": "Optimize fuzzy::eq(), add mixed benchmark\n\nChecking for direct equality and ascii characters _significantly_\nimproves the performance of this method for anything that isn't UTF8.\n" }, { "from": "human", "value": "mod score;\npub mod consts;\n\npub use self::score::*;\n\n/// Compares two characters case-insensitively\n///\n/// # Examples\n///\n/// ```\n/// assert!(rff::fuzzy::eq('a', 'A'));\n/// ```\npub fn eq(a: char, b: char) -> bool {\n a.to_uppercase().eq(b.to_uppercase())\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use test::Bencher;\n\n #[test]\n fn test_eq() {\n assert!(eq('a', 'A'));\n assert!(eq('山', '山'));\n assert!(!eq('a', 'b'));\n }\n\n #[bench]\n fn bench_eq_same(b: &mut Bencher) {\n b.iter(|| eq('a', 'a'));\n }\n\n #[bench]\n fn bench_eq_ascii(b: &mut Bencher) {\n b.iter(|| eq('a', 'A'));\n }\n\n #[bench]\n fn bench_eq_utf8(b: &mut Bencher) {\n b.iter(|| eq('ø', 'Ø'));\n }\n}\n" }, { "from": "gpt", "value": "mod score;\npub mod consts;\n\nuse std::ascii::AsciiExt;\npub use self::score::*;\n\n/// Compares two characters case-insensitively\n///\n/// # Examples\n///\n/// ```\n/// assert!(rff::fuzzy::eq('a', 'A'));\n/// ```\npub fn eq(a: char, b: char) -> bool {\n match a {\n a if a == b => true,\n a if a.is_ascii() && !b.is_ascii() => false,\n a if !a.is_ascii() && b.is_ascii() => false,\n a if a.is_ascii() && b.is_ascii() => {\n a.to_ascii_lowercase().eq(&b.to_ascii_lowercase())\n },\n a => a.to_lowercase().eq(b.to_lowercase())\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use test::Bencher;\n\n #[test]\n fn test_eq() {\n assert!(eq('a', 'A'));\n assert!(eq('山', '山'));\n assert!(!eq('a', 'b'));\n }\n\n #[bench]\n fn bench_eq_same(b: &mut Bencher) {\n b.iter(|| eq('a', 'a'));\n }\n\n #[bench]\n fn bench_eq_ascii(b: &mut Bencher) {\n b.iter(|| eq('a', 'A'));\n }\n\n #[bench]\n fn bench_eq_utf8(b: &mut Bencher) {\n b.iter(|| eq('ø', 'Ø'));\n }\n\n #[bench]\n fn bench_eq_mixed(b: &mut Bencher) {\n b.iter(|| eq('a', 'Ø'));\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix broken test on musl\n" }, { "from": "human", "value": "// run-pass\n\n#![allow(dead_code)]\n// Static recursion check shouldn't fail when given a foreign item (#18279)\n\n// aux-build:check_static_recursion_foreign_helper.rs\n// ignore-wasm32-bare no libc to test ffi with\n\n// pretty-expanded FIXME #23616\n\n#![feature(rustc_private)]\n\nextern crate check_static_recursion_foreign_helper;\nextern crate libc;\n\nuse libc::c_int;\n\n#[link(name = \"check_static_recursion_foreign_helper\")]\nextern \"C\" {\n #[allow(dead_code)]\n static test_static: c_int;\n}\n\nstatic B: &'static c_int = unsafe { &test_static };\n\npub fn main() {}\n" }, { "from": "gpt", "value": "// run-pass\n\n// Static recursion check shouldn't fail when given a foreign item (#18279)\n\n// aux-build:check_static_recursion_foreign_helper.rs\n// ignore-wasm32-bare no libc to test ffi with\n\n// pretty-expanded FIXME #23616\n\n#![feature(rustc_private)]\n\nextern crate check_static_recursion_foreign_helper;\nextern crate libc;\n\nuse libc::c_int;\n\nextern \"C\" {\n static test_static: c_int;\n}\n\npub static B: &'static c_int = unsafe { &test_static };\n\npub fn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Rename result images in Perlin example\n\nCloses #158" }, { "from": "human", "value": "// Copyright 2015 The Noise-rs Developers.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//! An example of using perlin noise\n\nextern crate noise;\n\nuse noise::{Perlin, Seedable};\n\nmod debug;\n\nfn main() {\n debug::render_noise_module(\"perlin.png\", Perlin::new(), 1024, 1024, 50);\n debug::render_noise_module(\"perlin.png\", Perlin::new().set_seed(1), 1024, 1024, 50);\n}\n" }, { "from": "gpt", "value": "// Copyright 2015 The Noise-rs Developers.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//! An example of using perlin noise\n\nextern crate noise;\n\nuse noise::{Perlin, Seedable};\n\nmod debug;\n\nfn main() {\n debug::render_noise_module(\"perlin1.png\", Perlin::new(), 1024, 1024, 50);\n debug::render_noise_module(\"perlin2.png\", Perlin::new().set_seed(1), 1024, 1024, 50);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "x86_64-unknown-none: Use position-independent code by default\n\nThis avoids requiring relocation code, which a bare-metal environment\nmay not have or want.\n" }, { "from": "human", "value": "// Generic AArch64 target for bare-metal code - Floating point enabled\n//\n// Can be used in conjunction with the `target-feature` and\n// `target-cpu` compiler flags to opt-in more hardware-specific\n// features.\n//\n// For example, `-C target-cpu=cortex-a53`.\n\nuse super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};\n\npub fn target() -> Target {\n let opts = TargetOptions {\n linker_flavor: LinkerFlavor::Lld(LldFlavor::Ld),\n linker: Some(\"rust-lld\".to_owned()),\n features: \"+strict-align,+neon,+fp-armv8\".to_string(),\n executables: true,\n relocation_model: RelocModel::Static,\n disable_redzone: true,\n max_atomic_width: Some(128),\n panic_strategy: PanicStrategy::Abort,\n ..Default::default()\n };\n Target {\n llvm_target: \"aarch64-unknown-none\".to_string(),\n pointer_width: 64,\n data_layout: \"e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128\".to_string(),\n arch: \"aarch64\".to_string(),\n options: opts,\n }\n}\n" }, { "from": "gpt", "value": "// Generic AArch64 target for bare-metal code - Floating point enabled\n//\n// Can be used in conjunction with the `target-feature` and\n// `target-cpu` compiler flags to opt-in more hardware-specific\n// features.\n//\n// For example, `-C target-cpu=cortex-a53`.\n\nuse super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};\n\npub fn target() -> Target {\n let opts = TargetOptions {\n linker_flavor: LinkerFlavor::Lld(LldFlavor::Ld),\n linker: Some(\"rust-lld\".to_owned()),\n features: \"+strict-align,+neon,+fp-armv8\".to_string(),\n executables: true,\n relocation_model: RelocModel::Pic,\n disable_redzone: true,\n max_atomic_width: Some(128),\n panic_strategy: PanicStrategy::Abort,\n ..Default::default()\n };\n Target {\n llvm_target: \"aarch64-unknown-none\".to_string(),\n pointer_width: 64,\n data_layout: \"e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128\".to_string(),\n arch: \"aarch64\".to_string(),\n options: opts,\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": ":art: Make possible to write alfred items\n\n" }, { "from": "human", "value": "extern crate alfred;\n\nuse config::Config;\nuse jira_api::SearchIssue;\nuse jira_client;\nuse search_response::SearchResponse;\n\nstruct SearchCommand {\n pub config: Config,\n}\n\nimpl SearchCommand {\n pub fn run(&self, keyword: &String) -> Result<String, String> {\n let jira_search = SearchIssue{\n config: self.config.clone(),\n keyword: keyword.to_string(),\n };\n let issues = jira_client::send::<SearchIssue, SearchResponse>(jira_search).map_err(|e| e.to_string())?;\n Ok(\"\".to_string())\n }\n}" }, { "from": "gpt", "value": "extern crate alfred;\n\nuse config::Config;\nuse jira_api::SearchIssue;\nuse jira_client;\nuse search_response::SearchResponse;\nuse std::io::{self, Write};\n\npub struct SearchCommand {\n pub config: Config,\n}\n\nimpl SearchCommand {\n pub fn run(&self, keyword: &String) -> Result<(), String> {\n let jira_search = SearchIssue{\n config: self.config.clone(),\n keyword: keyword.to_string(),\n };\n let res = jira_client::send::<SearchIssue, SearchResponse>(jira_search).map_err(|e| e.to_string())?;\n Ok(self.write_alfred_items(res))\n }\n\n fn write_alfred_items(&self, res: SearchResponse) {\n let alfred_items = res.issues.into_iter()\n .map(|issue| alfred::ItemBuilder::new(issue.key).arg(issue.url).into_item())\n .collect::<Vec<alfred::Item>>();\n\n alfred::json::write_items(io::stdout(), &alfred_items);\n }\n}" } ]
rust
chosen
[ { "from": "system", "value": "Use correct version of cargo in test\n" }, { "from": "human", "value": "use cargo_test_support::compare::assert_ui;\nuse cargo_test_support::curr_dir;\nuse cargo_test_support::CargoCommand;\nuse cargo_test_support::Project;\nuse cargo_test_support::TestEnv;\n\nuse crate::cargo_remove::init_registry;\n\n#[cargo_test]\nfn case() {\n init_registry();\n let project = Project::from_template(curr_dir!().join(\"in\"));\n let project_root = project.root();\n let cwd = &project_root;\n\n // run the metadata command to populate the cache\n let cargo = std::env::var_os(\"CARGO\").unwrap();\n snapbox::cmd::Command::new(cargo)\n .test_env()\n .arg(\"metadata\")\n .current_dir(cwd)\n .assert()\n .success();\n\n snapbox::cmd::Command::cargo_ui()\n .arg(\"remove\")\n .args([\"docopt\", \"--offline\"])\n .current_dir(cwd)\n .assert()\n .success()\n .stdout_matches_path(curr_dir!().join(\"stdout.log\"))\n .stderr_matches_path(curr_dir!().join(\"stderr.log\"));\n\n assert_ui().subset_matches(curr_dir!().join(\"out\"), &project_root);\n}\n" }, { "from": "gpt", "value": "use cargo_test_support::compare::assert_ui;\nuse cargo_test_support::curr_dir;\nuse cargo_test_support::CargoCommand;\nuse cargo_test_support::Project;\n\nuse crate::cargo_remove::init_registry;\n\n#[cargo_test]\nfn case() {\n init_registry();\n let project = Project::from_template(curr_dir!().join(\"in\"));\n let project_root = project.root();\n let cwd = &project_root;\n\n // run the metadata command to populate the cache\n snapbox::cmd::Command::cargo_ui()\n .arg(\"metadata\")\n .current_dir(cwd)\n .assert()\n .success();\n\n snapbox::cmd::Command::cargo_ui()\n .arg(\"remove\")\n .args([\"docopt\", \"--offline\"])\n .current_dir(cwd)\n .assert()\n .success()\n .stdout_matches_path(curr_dir!().join(\"stdout.log\"))\n .stderr_matches_path(curr_dir!().join(\"stderr.log\"));\n\n assert_ui().subset_matches(curr_dir!().join(\"out\"), &project_root);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "net/conn: Add type EthernetRule, NetworkRule and TransportRule\n" }, { "from": "human", "value": "//! Definition of various types related to connexions\n\n/// Type of the ether_type\npub type EtherType = u16;\n/// Type that represent a protocol id\npub type ProtocolIdType = u8;\n/// Type that represent a port\npub type PortType = u16;\n" }, { "from": "gpt", "value": "//! Definition of various types related to connexions\n\nuse net::defs::{HwAddr, IpAddr};\n\n/// Type of the ether_type\npub type EtherType = u16;\n/// Type that represent a protocol id\npub type ProtocolIdType = u8;\n/// Type that represent a port\npub type PortType = u16;\n\n/// Ethernet layer part of the rule\npub struct EthernetRule {\n pub ether_type: EtherType,\n pub hw_src: Option<HwAddr>,\n}\n\n/// Network layer part of the rule\npub struct NetworkRule {\n pub protocol_id: ProtocolIdType,\n pub ip_src: Option<IpAddr>,\n}\n\n/// Transport layer part of the rule\npub struct TransportRule {\n pub port: PortType,\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Disable const item mutation warning (triggers on pointers)\n" }, { "from": "human", "value": "#![feature(const_fn)]\n#![feature(extern_types)]\n#![feature(or_patterns)]\n\n#[cfg(test)]\n#[macro_use]\nextern crate quickcheck;\n\n#[macro_use]\nmod dbg;\n\n#[macro_use]\nmod paging;\n\npub mod cpu;\n\npub mod js_api;\npub mod profiler;\n\nmod analysis;\nmod codegen;\nmod config;\nmod cpu_context;\nmod gen;\nmod jit;\nmod jit_instructions;\nmod leb;\nmod modrm;\nmod opstats;\nmod page;\nmod prefix;\nmod regs;\nmod softfloat;\nmod state_flags;\nmod util;\nmod wasmgen;\n" }, { "from": "gpt", "value": "#![feature(const_fn)]\n#![feature(extern_types)]\n#![feature(or_patterns)]\n#![allow(const_item_mutation)]\n\n#[cfg(test)]\n#[macro_use]\nextern crate quickcheck;\n\n#[macro_use]\nmod dbg;\n\n#[macro_use]\nmod paging;\n\npub mod cpu;\n\npub mod js_api;\npub mod profiler;\n\nmod analysis;\nmod codegen;\nmod config;\nmod cpu_context;\nmod gen;\nmod jit;\nmod jit_instructions;\nmod leb;\nmod modrm;\nmod opstats;\nmod page;\nmod prefix;\nmod regs;\nmod softfloat;\nmod state_flags;\nmod util;\nmod wasmgen;\n" } ]
rust
chosen
[ { "from": "system", "value": "Add p macro for tests\n" }, { "from": "human", "value": "extern crate native_tls;\n\npub use native_tls::*;\n" }, { "from": "gpt", "value": "extern crate native_tls;\n\npub use native_tls::*;\n\n\nmacro_rules! p {\n ($e:expr) => {\n match $e {\n Ok(r) => r,\n Err(e) => panic!(\"{:?}\", e),\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix sub-breakage due to the changed error message.\n" }, { "from": "human", "value": "class c { //~ ERROR a class must have at least one field\n new() { }\n}\n\nfn main() {\n let a = c();\n let x = ~[a];\n let _y = x[0];\n}\n" }, { "from": "gpt", "value": "class c { //~ ERROR a struct must have at least one field\n new() { }\n}\n\nfn main() {\n let a = c();\n let x = ~[a];\n let _y = x[0];\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix for 1.2.0-nightly (613e57b44 2015-06-01)\n" }, { "from": "human", "value": "// This whole file is strongly inspired by: https://github.com/jeaye/q3/blob/master/src/client/ui/ttf/glyph.rs\n// available under the BSD-3 licence.\n// It has been modified to work with gl-rs, nalgebra, and rust-freetype\n\nuse na::Vec2;\n\n#[packed]\n/// A ttf glyph.\npub struct Glyph {\n #[doc(hidden)]\n pub tex: Vec2<f32>,\n #[doc(hidden)]\n pub advance: Vec2<f32>,\n #[doc(hidden)]\n pub dimensions: Vec2<f32>,\n #[doc(hidden)]\n pub offset: Vec2<f32>,\n #[doc(hidden)]\n pub buffer: Vec<u8>\n}\n\nimpl Glyph {\n /// Creates a new empty glyph.\n pub fn new(tex: Vec2<f32>,\n advance: Vec2<f32>,\n dimensions: Vec2<f32>,\n offset: Vec2<f32>,\n buffer: Vec<u8>)\n -> Glyph {\n Glyph {\n tex: tex,\n advance: advance,\n dimensions: dimensions,\n offset: offset,\n buffer: buffer\n }\n }\n}\n" }, { "from": "gpt", "value": "// This whole file is strongly inspired by: https://github.com/jeaye/q3/blob/master/src/client/ui/ttf/glyph.rs\n// available under the BSD-3 licence.\n// It has been modified to work with gl-rs, nalgebra, and rust-freetype\n\nuse na::Vec2;\n\n#[repr(packed)]\n/// A ttf glyph.\npub struct Glyph {\n #[doc(hidden)]\n pub tex: Vec2<f32>,\n #[doc(hidden)]\n pub advance: Vec2<f32>,\n #[doc(hidden)]\n pub dimensions: Vec2<f32>,\n #[doc(hidden)]\n pub offset: Vec2<f32>,\n #[doc(hidden)]\n pub buffer: Vec<u8>\n}\n\nimpl Glyph {\n /// Creates a new empty glyph.\n pub fn new(tex: Vec2<f32>,\n advance: Vec2<f32>,\n dimensions: Vec2<f32>,\n offset: Vec2<f32>,\n buffer: Vec<u8>)\n -> Glyph {\n Glyph {\n tex: tex,\n advance: advance,\n dimensions: dimensions,\n offset: offset,\n buffer: buffer\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update fuzzer script with upper size bound\n" }, { "from": "human", "value": "#![no_main]\n#[macro_use] extern crate libfuzzer_sys;\nextern crate image;\n\nfuzz_target!(|data: &[u8]| {\n let _ = image::load_from_memory_with_format(data, image::ImageFormat::Tga);\n});\n" }, { "from": "gpt", "value": "#![no_main]\n#[macro_use] extern crate libfuzzer_sys;\nextern crate image;\n\nfuzz_target!(|data: &[u8]| {\n let _ = decode(data);\n});\n\nfn decode(data: &[u8]) -> Result<(), image::ImageError> {\n use image::ImageDecoder;\n let decoder = image::codecs::tga::TgaDecoder::new(std::io::Cursor::new(data))?;\n if decoder.total_bytes() > 4_000_000 {\n return Ok(());\n }\n let mut buffer = vec![0; decoder.total_bytes() as usize];\n decoder.read_image(&mut buffer)?;\n Ok(())\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update the compile-fail-fulldeps tests with new isize/usize literal suffixes.\n" }, { "from": "human", "value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// aux-build:use_from_trait_xc.rs\n\nextern crate use_from_trait_xc;\npub use use_from_trait_xc::Trait;\n\nfn main() {\n match () {\n Trait { x: 42u } => () //~ ERROR use of trait `Trait` in a struct pattern\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\n// aux-build:use_from_trait_xc.rs\n\nextern crate use_from_trait_xc;\npub use use_from_trait_xc::Trait;\n\nfn main() {\n match () {\n Trait { x: 42us } => () //~ ERROR use of trait `Trait` in a struct pattern\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix rustdoc const generics test\n" }, { "from": "human", "value": "// ignore-tidy-linelength\n\n#![feature(const_generics)]\n\n#![crate_name = \"foo\"]\n\npub enum Order {\n Sorted,\n Unsorted,\n}\n\n// @has foo/struct.VSet.html '//pre[@class=\"rust struct\"]' 'pub struct VSet<T, const ORDER: Order>'\n// @has foo/struct.VSet.html '//h3[@id=\"impl-Send\"]/code' 'impl<const ORDER: Order, T> Send for VSet<T, ORDER>'\n// @has foo/struct.VSet.html '//h3[@id=\"impl-Sync\"]/code' 'impl<const ORDER: Order, T> Sync for VSet<T, ORDER>'\npub struct VSet<T, const ORDER: Order> {\n inner: Vec<T>,\n}\n\n// @has foo/struct.VSet.html '//h3[@id=\"impl\"]/code' 'impl<T> VSet<T, { Order::Sorted }>'\nimpl <T> VSet<T, {Order::Sorted}> {\n pub fn new() -> Self {\n Self { inner: Vec::new() }\n }\n}\n\n// @has foo/struct.VSet.html '//h3[@id=\"impl-1\"]/code' 'impl<T> VSet<T, { Order::Unsorted }>'\nimpl <T> VSet<T, {Order::Unsorted}> {\n pub fn new() -> Self {\n Self { inner: Vec::new() }\n }\n}\n" }, { "from": "gpt", "value": "// ignore-tidy-linelength\n\n#![feature(const_generics)]\n\n#![crate_name = \"foo\"]\n\n#[derive(PartialEq, Eq)]\npub enum Order {\n Sorted,\n Unsorted,\n}\n\n// @has foo/struct.VSet.html '//pre[@class=\"rust struct\"]' 'pub struct VSet<T, const ORDER: Order>'\n// @has foo/struct.VSet.html '//h3[@id=\"impl-Send\"]/code' 'impl<const ORDER: Order, T> Send for VSet<T, ORDER>'\n// @has foo/struct.VSet.html '//h3[@id=\"impl-Sync\"]/code' 'impl<const ORDER: Order, T> Sync for VSet<T, ORDER>'\npub struct VSet<T, const ORDER: Order> {\n inner: Vec<T>,\n}\n\n// @has foo/struct.VSet.html '//h3[@id=\"impl\"]/code' 'impl<T> VSet<T, { Order::Sorted }>'\nimpl <T> VSet<T, {Order::Sorted}> {\n pub fn new() -> Self {\n Self { inner: Vec::new() }\n }\n}\n\n// @has foo/struct.VSet.html '//h3[@id=\"impl-1\"]/code' 'impl<T> VSet<T, { Order::Unsorted }>'\nimpl <T> VSet<T, {Order::Unsorted}> {\n pub fn new() -> Self {\n Self { inner: Vec::new() }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make the setenv tests threadsafe(ish)\n" }, { "from": "human", "value": "import std::generic_os::setenv;\nimport std::generic_os::getenv;\nimport std::option;\n\n#[test]\nfn test_setenv() {\n setenv(\"NAME\", \"VALUE\");\n assert getenv(\"NAME\") == option::some(\"VALUE\");\n}\n\n#[test]\nfn test_setenv_overwrite() {\n setenv(\"NAME\", \"1\");\n setenv(\"NAME\", \"2\");\n assert getenv(\"NAME\") == option::some(\"2\");\n}\n\n// Windows GetEnvironmentVariable requires some extra work to make sure\n// the buffer the variable is copied into is the right size\n#[test]\nfn test_getenv_big() {\n auto s = \"\";\n auto i = 0;\n while (i < 100) {\n s += \"aaaaaaaaaa\";\n i += 1;\n }\n setenv(\"NAME\", s);\n assert getenv(\"NAME\") == option::some(s);\n}\n\n// Local Variables:\n// mode: rust;\n// fill-column: 78;\n// indent-tabs-mode: nil\n// c-basic-offset: 4\n// buffer-file-coding-system: utf-8-unix\n// compile-command: \"make -k -C .. 2>&1 | sed -e 's/\\\\/x\\\\//x:\\\\//g'\";\n// End:\n" }, { "from": "gpt", "value": "import std::generic_os::setenv;\nimport std::generic_os::getenv;\nimport std::option;\n\n#[test]\nfn test_setenv() {\n // NB: Each test of setenv needs to use different variable names or the\n // tests will not be threadsafe\n setenv(\"NAME1\", \"VALUE\");\n assert getenv(\"NAME1\") == option::some(\"VALUE\");\n}\n\n#[test]\nfn test_setenv_overwrite() {\n setenv(\"NAME2\", \"1\");\n setenv(\"NAME2\", \"2\");\n assert getenv(\"NAME2\") == option::some(\"2\");\n}\n\n// Windows GetEnvironmentVariable requires some extra work to make sure\n// the buffer the variable is copied into is the right size\n#[test]\nfn test_getenv_big() {\n auto s = \"\";\n auto i = 0;\n while (i < 100) {\n s += \"aaaaaaaaaa\";\n i += 1;\n }\n setenv(\"NAME3\", s);\n assert getenv(\"NAME3\") == option::some(s);\n}\n\n// Local Variables:\n// mode: rust;\n// fill-column: 78;\n// indent-tabs-mode: nil\n// c-basic-offset: 4\n// buffer-file-coding-system: utf-8-unix\n// compile-command: \"make -k -C .. 2>&1 | sed -e 's/\\\\/x\\\\//x:\\\\//g'\";\n// End:\n" } ]
rust
chosen
[ { "from": "system", "value": "Handle missing cfitsio on pkg-config path\n" }, { "from": "human", "value": "extern crate pkg_config;\n\nfn main() {\n println!(\"cargo:rerun-if-changed=build.rs\");\n pkg_config::probe_library(\"cfitsio\").unwrap();\n}\n" }, { "from": "gpt", "value": "extern crate pkg_config;\n\nuse std::io::Write;\nuse pkg_config::Error;\n\nfn main() {\n\n let package_name = \"cfitsio\";\n match pkg_config::probe_library(package_name) {\n Ok(_) => {}\n Err(Error::Failure { output, .. }) => {\n // Handle the case where the user has not installed cfitsio, and thusly it is not on\n // the PKG_CONFIG_PATH\n let stderr = String::from_utf8(output.stderr).unwrap();\n if stderr.contains::<&str>(format!(\"{} was not found in the pkg-config search path\",\n package_name)\n .as_ref()) {\n let err_msg = format!(\"\nCannot find {} on the pkg-config search path. Consider installing the library for your\nsystem (e.g. through homebrew, apt-get etc.). Alternatively if it is installed, then add\nthe directory that contains `cfitsio.pc` on your PKG_CONFIG_PATH, e.g.:\n\nPKG_CONFIG_PATH=<blah> cargo build\n\",\n package_name);\n std::io::stderr().write(err_msg.as_bytes()).unwrap();\n std::process::exit(output.status.code().unwrap());\n }\n }\n Err(e) => panic!(\"Unhandled error: {:?}\", e),\n };\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "[generate-format] Remove the extra empty line at EOF\n\nThe extra empty line at EOF when generating YAML specification for\nmessage formats will cause the linter to panic. We fix it in this\ncommit.\n\nCloses: #8816\n" }, { "from": "human", "value": "// Copyright (c) The Diem Core Contributors\n// SPDX-License-Identifier: Apache-2.0\n\nuse generate_format::Corpus;\nuse std::{fs::File, io::Write};\nuse structopt::StructOpt;\n\n#[derive(Debug, StructOpt)]\n#[structopt(\n name = \"Diem format generator\",\n about = \"Trace serde (de)serialization to generate format descriptions for Diem types\"\n)]\nstruct Options {\n #[structopt(long, possible_values = &Corpus::variants(), default_value = \"Diem\", case_insensitive = true)]\n corpus: Corpus,\n\n #[structopt(long)]\n record: bool,\n}\n\nfn main() {\n let options = Options::from_args();\n\n let registry = options.corpus.get_registry();\n let output_file = options.corpus.output_file();\n\n let content = serde_yaml::to_string(&registry).unwrap();\n if options.record {\n match output_file {\n Some(path) => {\n let mut f = File::create(\"testsuite/generate-format/\".to_string() + path).unwrap();\n writeln!(f, \"{}\", content).unwrap();\n }\n None => panic!(\"Corpus {:?} doesn't record formats on disk\", options.corpus),\n }\n } else {\n println!(\"{}\", content);\n }\n}\n" }, { "from": "gpt", "value": "// Copyright (c) The Diem Core Contributors\n// SPDX-License-Identifier: Apache-2.0\n\nuse generate_format::Corpus;\nuse std::{fs::File, io::Write};\nuse structopt::StructOpt;\n\n#[derive(Debug, StructOpt)]\n#[structopt(\n name = \"Diem format generator\",\n about = \"Trace serde (de)serialization to generate format descriptions for Diem types\"\n)]\nstruct Options {\n #[structopt(long, possible_values = &Corpus::variants(), default_value = \"Diem\", case_insensitive = true)]\n corpus: Corpus,\n\n #[structopt(long)]\n record: bool,\n}\n\nfn main() {\n let options = Options::from_args();\n\n let registry = options.corpus.get_registry();\n let output_file = options.corpus.output_file();\n\n let content = serde_yaml::to_string(&registry).unwrap();\n if options.record {\n match output_file {\n Some(path) => {\n let mut f = File::create(\"testsuite/generate-format/\".to_string() + path).unwrap();\n write!(f, \"{}\", content).unwrap();\n }\n None => panic!(\"Corpus {:?} doesn't record formats on disk\", options.corpus),\n }\n } else {\n println!(\"{}\", content);\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix example to hnadle result.\n" }, { "from": "human", "value": "extern crate lcm;\n\nmod exlcm {\n include!(concat!(env!(\"OUT_DIR\"), \"/exlcm/example_t.rs\"));\n}\n\nfn main() {\n let mut lcm = lcm::Lcm::new();\n\n let mut my_data = exlcm::ExampleT::new();\n // let mut my_data = exlcm::Example::new();\n my_data.timestamp = 0;\n\n my_data.position[0] = 1.0;\n my_data.position[1] = 2.0;\n my_data.position[2] = 3.0;\n\n my_data.orientation[0] = 1.0;\n my_data.orientation[1] = 0.0;\n my_data.orientation[2] = 0.0;\n my_data.orientation[3] = 0.0;\n\n my_data.num_ranges = 15;\n my_data.ranges = (0..15).collect();\n\n my_data.name = \"example string\".to_string();\n my_data.enabled = true;\n\n match lcm.publish(\"EXAMPLE\", &my_data) {\n Ok(()) => println!(\"Sent message.\"),\n Err(e) => println!(\"Failed to send message: {}\", e)\n }\n}\n" }, { "from": "gpt", "value": "extern crate lcm;\n\nmod exlcm {\n include!(concat!(env!(\"OUT_DIR\"), \"/exlcm/example_t.rs\"));\n}\n\nfn main() {\n let mut lcm = lcm::Lcm::new().unwrap();\n\n let mut my_data = exlcm::ExampleT::new();\n // let mut my_data = exlcm::Example::new();\n my_data.timestamp = 0;\n\n my_data.position[0] = 1.0;\n my_data.position[1] = 2.0;\n my_data.position[2] = 3.0;\n\n my_data.orientation[0] = 1.0;\n my_data.orientation[1] = 0.0;\n my_data.orientation[2] = 0.0;\n my_data.orientation[3] = 0.0;\n\n my_data.num_ranges = 15;\n my_data.ranges = (0..15).collect();\n\n my_data.name = \"example string\".to_string();\n my_data.enabled = true;\n\n match lcm.publish(\"EXAMPLE\", &my_data) {\n Ok(()) => println!(\"Sent message.\"),\n Err(e) => println!(\"Failed to send message: {}\", e)\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "fix(rustup): Update serde_codegen to reflect Registry move\n" }, { "from": "human", "value": "#![feature(plugin_registrar, rustc_private)]\n\nextern crate serde_codegen;\nextern crate rustc;\n\n#[plugin_registrar]\n#[doc(hidden)]\npub fn plugin_registrar(reg: &mut rustc::plugin::Registry) {\n serde_codegen::register(reg);\n}\n" }, { "from": "gpt", "value": "#![feature(plugin_registrar, rustc_private)]\n\nextern crate serde_codegen;\nextern crate rustc_plugin;\n\n#[plugin_registrar]\n#[doc(hidden)]\npub fn plugin_registrar(reg: &mut rustc_plugin::Registry) {\n serde_codegen::register(reg);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix a warning in plugin compile tests\n" }, { "from": "human", "value": "/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nextern crate compiletest_helper;\n#[macro_use]\nextern crate deny_public_fields;\n\n#[test]\nfn compile_test() {\n compiletest_helper::run_mode(\"compile-fail\");\n}\n" }, { "from": "gpt", "value": "/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nextern crate compiletest_helper;\n\n#[test]\nfn compile_test() {\n compiletest_helper::run_mode(\"compile-fail\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use environment variable in the example\n\nThis will help in reproducing problems in nightly builds.\n" }, { "from": "human", "value": "extern crate randomorg;\n\nfn main() {\n use randomorg::Random;\n\n let r = Random::new(\"API KEY HERE\");\n println!(\"Result: {:?}\", r.generate_integers(-100, 100, 15, true));\n}\n" }, { "from": "gpt", "value": "extern crate randomorg;\n\nfn main() {\n use std::env;\n use randomorg::Random;\n\n let r = Random::new(env::var(\"RANDOM_ORG_API_KEY\").unwrap());\n println!(\"Result: {:?}\", r.generate_integers(-100, 100, 15, true).unwrap());\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Address LLVM assertion failure by prepopulating with *just* name-anon-globals.\n" }, { "from": "human", "value": "// Copyright 2018 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// run-pass\n// Test for issue #18804, #[linkage] does not propagate through generic\n// functions. Failure results in a linker error.\n\n// ignore-asmjs no weak symbol support\n// ignore-emscripten no weak symbol support\n// ignore-windows no extern_weak linkage\n// ignore-macos no extern_weak linkage\n\n// aux-build:lib.rs\n\n// rust-lang/rust#56772: nikic says we need this to be proper test.\n// compile-flags: -C no-prepopulate-passes\n\nextern crate lib;\n\nfn main() {\n lib::foo::<i32>();\n}\n" }, { "from": "gpt", "value": "// Copyright 2018 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// run-pass\n// Test for issue #18804, #[linkage] does not propagate through generic\n// functions. Failure results in a linker error.\n\n// ignore-asmjs no weak symbol support\n// ignore-emscripten no weak symbol support\n// ignore-windows no extern_weak linkage\n// ignore-macos no extern_weak linkage\n\n// aux-build:lib.rs\n\n// rust-lang/rust#56772: nikic says we need this to be proper test.\n// compile-flags: -C no-prepopulate-passes -C passes=name-anon-globals\n\nextern crate lib;\n\nfn main() {\n lib::foo::<i32>();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make a more meaningful test for Punct eq\n" }, { "from": "human", "value": "use proc_macro::{LineColumn, Punct};\n\npub fn test() {\n test_line_column_ord();\n test_punct_eq();\n}\n\nfn test_line_column_ord() {\n let line0_column0 = LineColumn { line: 0, column: 0 };\n let line0_column1 = LineColumn { line: 0, column: 1 };\n let line1_column0 = LineColumn { line: 1, column: 0 };\n assert!(line0_column0 < line0_column1);\n assert!(line0_column1 < line1_column0);\n}\n\nfn test_punct_eq() {\n // Good enough if it typechecks, since proc_macro::Punct can't exist in a test.\n fn _check(punct: Punct) {\n let _ = punct == ':';\n }\n}\n" }, { "from": "gpt", "value": "use proc_macro::{LineColumn, Punct, Spacing};\n\npub fn test() {\n test_line_column_ord();\n test_punct_eq();\n}\n\nfn test_line_column_ord() {\n let line0_column0 = LineColumn { line: 0, column: 0 };\n let line0_column1 = LineColumn { line: 0, column: 1 };\n let line1_column0 = LineColumn { line: 1, column: 0 };\n assert!(line0_column0 < line0_column1);\n assert!(line0_column1 < line1_column0);\n}\n\nfn test_punct_eq() {\n let colon_alone = Punct::new(':', Spacing::Alone);\n assert_eq!(colon_alone, ':');\n let colon_joint = Punct::new(':', Spacing::Joint);\n assert_eq!(colon_joint, ':');\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove 'use' line that's confusing pp-exact during use/import transition.\n" }, { "from": "human", "value": "#!/usr/bin/env rustx\n// pp-exact\n\nuse io::println;\n\nfn main() { io::println(~\"Hello World\"); }\n" }, { "from": "gpt", "value": "#!/usr/bin/env rustx\n// pp-exact\n\nfn main() { io::println(\"Hello World\"); }\n" } ]
rust
chosen
[ { "from": "system", "value": "Add some work on RenderCommandEncoder\n" }, { "from": "human", "value": "use cocoa::base::id;\n\npub struct RenderCommandEncoder(id);\n\nimpl_from_into_raw!(RenderCommandEncoder, of protocol \"MTLRenderCommandEncoder\");\n" }, { "from": "gpt", "value": "use cocoa::base::id;\nuse {DepthStencilState, RenderPipelineState};\n\npub struct RenderCommandEncoder(id);\n\nimpl RenderCommandEncoder {\n pub fn set_blend_color(&mut self, red: f32, green: f32, blue: f32, alpha: f32) {\n unimplemented!();\n }\n\n pub fn set_cull_mode(&mut self, cull_mode: CullMode) {\n unimplemented!();\n }\n\n pub fn set_depth_bias_with_slope_and_clamp(&mut self, depth_bias: f32, slope: f32, clamp: f32) {\n unimplemented!();\n }\n\n pub fn set_depth_clip_mode(&mut self, depth_clip_mode: DepthClipMode) {\n unimplemented!();\n }\n\n pub fn set_depth_stencil_state(&mut self, depth_stencil_state: &DepthStencilState) {\n unimplemented!();\n }\n\n pub fn set_front_facing_winding(&mut self, winding: Winding) {\n unimplemented!();\n }\n}\n\nimpl_from_into_raw!(RenderCommandEncoder, of protocol \"MTLRenderCommandEncoder\");\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\npub enum CullMode {\n None,\n Front,\n Back\n}\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\npub enum DepthClipMode {\n Clip,\n Clamp\n}\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\npub enum Winding {\n Clockwise,\n CounterClockwise\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Rename C-like enum to Field-less enum\n\nThere is no need to reference the C programming language to explain this concept." }, { "from": "human", "value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// compile-flags: -Z parse-only\n\n//error-pattern: discriminator values can only be used with a c-like enum\n\nenum color {\n red = 0xff0000,\n green = 0x00ff00,\n blue = 0x0000ff,\n black = 0x000000,\n white = 0xffffff,\n other (str),\n}\n" }, { "from": "gpt", "value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// compile-flags: -Z parse-only\n\n//error-pattern: discriminator values can only be used with a field-less enum\n\nenum color {\n red = 0xff0000,\n green = 0x00ff00,\n blue = 0x0000ff,\n black = 0x000000,\n white = 0xffffff,\n other (str),\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add safety comment to StableAddress impl for Mmap\n" }, { "from": "human", "value": "use std::fs::File;\nuse std::io;\nuse std::ops::Deref;\n\nuse crate::owning_ref::StableAddress;\n\n/// A trivial wrapper for [`memmap2::Mmap`] that implements [`StableAddress`].\n#[cfg(not(target_arch = \"wasm32\"))]\npub struct Mmap(memmap2::Mmap);\n\n#[cfg(target_arch = \"wasm32\")]\npub struct Mmap(Vec<u8>);\n\n#[cfg(not(target_arch = \"wasm32\"))]\nimpl Mmap {\n #[inline]\n pub unsafe fn map(file: File) -> io::Result<Self> {\n memmap2::Mmap::map(&file).map(Mmap)\n }\n}\n\n#[cfg(target_arch = \"wasm32\")]\nimpl Mmap {\n #[inline]\n pub unsafe fn map(mut file: File) -> io::Result<Self> {\n use std::io::Read;\n\n let mut data = Vec::new();\n file.read_to_end(&mut data)?;\n Ok(Mmap(data))\n }\n}\n\nimpl Deref for Mmap {\n type Target = [u8];\n\n #[inline]\n fn deref(&self) -> &[u8] {\n &*self.0\n }\n}\n\nunsafe impl StableAddress for Mmap {}\n" }, { "from": "gpt", "value": "use std::fs::File;\nuse std::io;\nuse std::ops::Deref;\n\nuse crate::owning_ref::StableAddress;\n\n/// A trivial wrapper for [`memmap2::Mmap`] that implements [`StableAddress`].\n#[cfg(not(target_arch = \"wasm32\"))]\npub struct Mmap(memmap2::Mmap);\n\n#[cfg(target_arch = \"wasm32\")]\npub struct Mmap(Vec<u8>);\n\n#[cfg(not(target_arch = \"wasm32\"))]\nimpl Mmap {\n #[inline]\n pub unsafe fn map(file: File) -> io::Result<Self> {\n memmap2::Mmap::map(&file).map(Mmap)\n }\n}\n\n#[cfg(target_arch = \"wasm32\")]\nimpl Mmap {\n #[inline]\n pub unsafe fn map(mut file: File) -> io::Result<Self> {\n use std::io::Read;\n\n let mut data = Vec::new();\n file.read_to_end(&mut data)?;\n Ok(Mmap(data))\n }\n}\n\nimpl Deref for Mmap {\n type Target = [u8];\n\n #[inline]\n fn deref(&self) -> &[u8] {\n &*self.0\n }\n}\n\n// SAFETY: On architectures other than WASM, mmap is used as backing storage. The address of this\n// memory map is stable. On WASM, `Vec<u8>` is used as backing storage. The `Mmap` type doesn't\n// export any function that can cause the `Vec` to be re-allocated. As such the address of the\n// bytes inside this `Vec` is stable.\nunsafe impl StableAddress for Mmap {}\n" } ]
rust
chosen
[ { "from": "system", "value": "events: Fix UI test failing with compat feature\n" }, { "from": "human", "value": "// rustc overflows when compiling this see:\n// https://github.com/rust-lang/rust/issues/55779\nextern crate serde;\n\nuse ruma_events::StateEventContent;\nuse ruma_events_macros::Event;\n\n/// State event.\n#[derive(Clone, Debug, Event)]\npub struct StateEvent<C: StateEventContent> {\n pub content: C,\n pub state_key: String,\n pub prev_content: Option<C>,\n}\n\nfn main() {}\n" }, { "from": "gpt", "value": "// rustc overflows when compiling this see:\n// https://github.com/rust-lang/rust/issues/55779\nextern crate serde;\n\nuse ruma_events::{StateEventContent, Unsigned};\nuse ruma_events_macros::Event;\n\n/// State event.\n#[derive(Clone, Debug, Event)]\npub struct StateEvent<C: StateEventContent> {\n pub content: C,\n pub state_key: String,\n pub prev_content: Option<C>,\n pub unsigned: Unsigned,\n}\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update the usage of random\n" }, { "from": "human", "value": "use probability::prelude::*;\nuse test::{Bencher, black_box};\n\n#[bench]\nfn cdf(bencher: &mut Bencher) {\n let mut source = random::default();\n let gaussian = Gaussian::new(0.0, 1.0);\n let x = Independent(&gaussian, &mut source).take(1000).collect::<Vec<_>>();\n\n bencher.iter(|| black_box(x.iter().map(|&x| gaussian.cdf(x)).collect::<Vec<_>>()));\n}\n\n#[bench]\nfn inv_cdf(bencher: &mut Bencher) {\n let mut source = random::default();\n let gaussian = Gaussian::new(0.0, 1.0);\n let uniform = Uniform::new(0.0, 1.0);\n let p = Independent(&uniform, &mut source).take(1000).collect::<Vec<_>>();\n\n bencher.iter(|| black_box(p.iter().map(|&p| gaussian.inv_cdf(p)).collect::<Vec<_>>()));\n}\n\n#[bench]\nfn sample(bencher: &mut Bencher) {\n let mut source = random::XorshiftPlus::new([42, 42]);\n let gaussian = Gaussian::new(0.0, 1.0);\n\n bencher.iter(|| black_box(gaussian.sample(&mut source)));\n}\n" }, { "from": "gpt", "value": "use probability::prelude::*;\nuse test::{Bencher, black_box};\n\n#[bench]\nfn cdf(bencher: &mut Bencher) {\n let mut source = random::default();\n let gaussian = Gaussian::new(0.0, 1.0);\n let x = Independent(&gaussian, &mut source).take(1000).collect::<Vec<_>>();\n\n bencher.iter(|| black_box(x.iter().map(|&x| gaussian.cdf(x)).collect::<Vec<_>>()));\n}\n\n#[bench]\nfn inv_cdf(bencher: &mut Bencher) {\n let mut source = random::default();\n let gaussian = Gaussian::new(0.0, 1.0);\n let uniform = Uniform::new(0.0, 1.0);\n let p = Independent(&uniform, &mut source).take(1000).collect::<Vec<_>>();\n\n bencher.iter(|| black_box(p.iter().map(|&p| gaussian.inv_cdf(p)).collect::<Vec<_>>()));\n}\n\n#[bench]\nfn sample(bencher: &mut Bencher) {\n let mut source = random::Xorshift128Plus::new([42, 69]);\n let gaussian = Gaussian::new(0.0, 1.0);\n\n bencher.iter(|| black_box(gaussian.sample(&mut source)));\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update autocargo component on FBS:master\n\nSummary:\nAutomated component version update\nBump Schedule: https://www.internalfb.com/intern/msdk/bump/?schedule_fbid=342556550408072\nPackage: https://www.internalfb.com/intern/msdk/package/125803836415945/\nOncall Team: rust_foundation\nNOTE: This build is expected to expire at 2022/10/11 06:06AM PDT\n---------\nNew project source changes since last bump based on 9cc37ee9d47923093119b37d4f2d60de5a5e490f at 2021/09/21 01:03PM UTC:\n| 2021/09/21 01:05PM -05 | generatedunixname89002005294178 | D31082067 | [MSDK] Update autocargo component on FBS:master |\n| 2021/09/29 01:58PM PDT | vgao1996 | D31115820 (https://github.com/facebook/fbthrift/commit/5b708efab9c17ed9797de50b0495cfc94d9964f7) | [Rust] update rand and quickcheck |\n| 2021/09/30 02:55PM PDT | jkeljo | D31284743 (https://github.com/facebook/fbthrift/commit/25587a6a95209b773a63b5060482a2c5995cca86) | [rust][third-party] Enable `unbounded_depth` feature for `serde_json` |\n| 2021/10/08 11:43AM BST | krallin | D31471849 | autocargo: emit rerun-if-changed on the buildscript itself |\n---------\n\nbuild-break (bot commits are not reviewed by a human)\n\nReviewed By: farnz\n\nDifferential Revision: D31541798\n\nfbshipit-source-id: 8e41a39d552c31a879c41b7d244e2caca047b7da\n" }, { "from": "human", "value": "// @generated by autocargo\nuse std::env;\nuse std::fs;\nuse std::path::Path;\n\nuse thrift_compiler::Config;\n\n#[rustfmt::skip]\nfn main() {\n let out_dir = env::var_os(\"OUT_DIR\").expect(\"OUT_DIR env not provided\");\n let out_dir: &Path = out_dir.as_ref();\n fs::write(\n out_dir.join(\"cratemap\"),\n \"test_thrift crate\",\n ).expect(\"Failed to write cratemap\");\n\n let conf = {\n let mut conf = Config::from_env().expect(\"Failed to instantiate thrift_compiler::Config\");\n\n let path_from_manifest_to_base: &Path = \"../../../../../..\".as_ref();\n let cargo_manifest_dir =\n env::var_os(\"CARGO_MANIFEST_DIR\").expect(\"CARGO_MANIFEST_DIR not provided\");\n let cargo_manifest_dir: &Path = cargo_manifest_dir.as_ref();\n let base_path = cargo_manifest_dir\n .join(path_from_manifest_to_base)\n .canonicalize()\n .expect(\"Failed to canonicalize base_path\");\n conf.base_path(base_path);\n\n let options = \"serde\";\n if !options.is_empty() {\n conf.options(options);\n }\n\n let include_srcs = vec![\n \n ];\n conf.include_srcs(include_srcs);\n\n conf\n };\n\n conf\n .run(&[\n \"../test_thrift.thrift\"\n ])\n .expect(\"Failed while running thrift compilation\");\n}\n" }, { "from": "gpt", "value": "// @generated by autocargo\nuse std::env;\nuse std::fs;\nuse std::path::Path;\n\nuse thrift_compiler::Config;\n\n#[rustfmt::skip]\nfn main() {\n // Rerun if this gets rewritten.\n println!(\"cargo:rerun-if-changed=thrift_build.rs\");\n\n let out_dir = env::var_os(\"OUT_DIR\").expect(\"OUT_DIR env not provided\");\n let out_dir: &Path = out_dir.as_ref();\n fs::write(\n out_dir.join(\"cratemap\"),\n \"test_thrift crate\",\n ).expect(\"Failed to write cratemap\");\n\n let conf = {\n let mut conf = Config::from_env().expect(\"Failed to instantiate thrift_compiler::Config\");\n\n let path_from_manifest_to_base: &Path = \"../../../../../..\".as_ref();\n let cargo_manifest_dir =\n env::var_os(\"CARGO_MANIFEST_DIR\").expect(\"CARGO_MANIFEST_DIR not provided\");\n let cargo_manifest_dir: &Path = cargo_manifest_dir.as_ref();\n let base_path = cargo_manifest_dir\n .join(path_from_manifest_to_base)\n .canonicalize()\n .expect(\"Failed to canonicalize base_path\");\n conf.base_path(base_path);\n\n let options = \"serde\";\n if !options.is_empty() {\n conf.options(options);\n }\n\n let include_srcs = vec![\n \n ];\n conf.include_srcs(include_srcs);\n\n conf\n };\n\n conf\n .run(&[\n \"../test_thrift.thrift\"\n ])\n .expect(\"Failed while running thrift compilation\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "federation-api: Fix link to old matrix-doc repo\n" }, { "from": "human", "value": "//! Endpoint to receive metadata about implemented matrix versions.\n\npub mod msc3723 {\n //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-doc/pull/3723)\n\n use ruma_common::api::ruma_api;\n\n ruma_api! {\n metadata: {\n description: \"Get the supported matrix versions of this homeserver\",\n method: GET,\n name: \"get_server_versions\",\n unstable_path: \"/_matrix/federation/unstable/org.matrix.msc3723/versions\",\n rate_limited: false,\n authentication: None,\n }\n\n #[derive(Default)]\n request: {}\n\n #[derive(Default)]\n response: {\n /// A list of Matrix Server API protocol versions supported by the homeserver.\n pub versions: Vec<String>,\n }\n }\n\n impl Request {\n /// Creates an empty `Request`.\n pub fn new() -> Self {\n Self {}\n }\n }\n\n impl Response {\n /// Creates an empty `Response`.\n pub fn new() -> Self {\n Default::default()\n }\n }\n}\n" }, { "from": "gpt", "value": "//! Endpoint to receive metadata about implemented matrix versions.\n\npub mod msc3723 {\n //! [GET /_matrix/federation/versions](https://github.com/matrix-org/matrix-spec-proposals/pull/3723)\n\n use ruma_common::api::ruma_api;\n\n ruma_api! {\n metadata: {\n description: \"Get the supported matrix versions of this homeserver\",\n method: GET,\n name: \"get_server_versions\",\n unstable_path: \"/_matrix/federation/unstable/org.matrix.msc3723/versions\",\n rate_limited: false,\n authentication: None,\n }\n\n #[derive(Default)]\n request: {}\n\n #[derive(Default)]\n response: {\n /// A list of Matrix Server API protocol versions supported by the homeserver.\n pub versions: Vec<String>,\n }\n }\n\n impl Request {\n /// Creates an empty `Request`.\n pub fn new() -> Self {\n Self {}\n }\n }\n\n impl Response {\n /// Creates an empty `Response`.\n pub fn new() -> Self {\n Default::default()\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add generic types to prelude collision lint test.\n" }, { "from": "human", "value": "// edition:2018\n// check-pass\n#![allow(unused)]\n#![deny(rust_2021_prelude_collisions)]\n\nstruct S;\n\nimpl S {\n fn try_into(self) -> S {\n S\n }\n}\n\nstruct X;\n\ntrait Hey {\n fn from_iter(_: i32) -> Self;\n}\n\nimpl Hey for X {\n fn from_iter(_: i32) -> Self {\n X\n }\n}\n\nfn main() {\n // See https://github.com/rust-lang/rust/issues/86633\n let s = S;\n let s2 = s.try_into();\n\n // See https://github.com/rust-lang/rust/issues/86902\n X::from_iter(1);\n}\n" }, { "from": "gpt", "value": "// edition:2018\n// check-pass\n#![allow(unused)]\n#![deny(rust_2021_prelude_collisions)]\n\nstruct S;\n\nimpl S {\n fn try_into(self) -> S {\n S\n }\n}\n\nstruct X;\n\ntrait Hey {\n fn from_iter(_: i32) -> Self;\n}\n\nimpl Hey for X {\n fn from_iter(_: i32) -> Self {\n X\n }\n}\n\nstruct Y<T>(T);\n\nimpl Hey for Y<i32> {\n fn from_iter(_: i32) -> Self {\n Y(0)\n }\n}\n\nstruct Z<T>(T);\n\nimpl Hey for Z<i32> {\n fn from_iter(_: i32) -> Self {\n Z(0)\n }\n}\n\nimpl std::iter::FromIterator<u32> for Z<u32> {\n fn from_iter<T: IntoIterator<Item = u32>>(_: T) -> Self {\n todo!()\n }\n}\n\nfn main() {\n // See https://github.com/rust-lang/rust/issues/86633\n let s = S;\n let s2 = s.try_into();\n\n // See https://github.com/rust-lang/rust/issues/86902\n X::from_iter(1);\n Y::from_iter(1);\n Y::<i32>::from_iter(1);\n Z::<i32>::from_iter(1);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use recommended pkg-config method to discover libfuse\n" }, { "from": "human", "value": "extern crate pkg_config;\n\nfn main () {\n pkg_config::probe_library(\"fuse\").unwrap();\n}\n" }, { "from": "gpt", "value": "extern crate pkg_config;\n\n#[cfg(not(target_os = \"macos\"))]\nstatic LIBFUSE_NAME: &str = \"fuse\";\n\n#[cfg(target_os = \"macos\")]\nstatic LIBFUSE_NAME: &str = \"osxfuse\";\n\nfn main () {\n pkg_config::Config::new().atleast_version(\"2.6.0\").probe(LIBFUSE_NAME).unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "docs: Fix copy paste error in example" }, { "from": "human", "value": "use clap::{app_from_crate, arg};\n\nfn main() {\n let matches = app_from_crate!()\n .arg(\n arg!(<PORT>)\n .help(\"Network port to use\")\n .validator(|s| s.parse::<usize>()),\n )\n .get_matches();\n\n // Note, it's safe to call unwrap() because the arg is required\n let port: usize = matches\n .value_of_t(\"PORT\")\n .expect(\"'MODE' is required and parsing will fail if its missing\");\n println!(\"PORT = {}\", port);\n}\n" }, { "from": "gpt", "value": "use clap::{app_from_crate, arg};\n\nfn main() {\n let matches = app_from_crate!()\n .arg(\n arg!(<PORT>)\n .help(\"Network port to use\")\n .validator(|s| s.parse::<usize>()),\n )\n .get_matches();\n\n // Note, it's safe to call unwrap() because the arg is required\n let port: usize = matches\n .value_of_t(\"PORT\")\n .expect(\"'PORT' is required and parsing will fail if its missing\");\n println!(\"PORT = {}\", port);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Rename `render_command_encoder` to `create_render_command_encoder` to emphasise that it creates a `RenderCommandEncoder`\n" }, { "from": "human", "value": "use cocoa::base::id;\nuse std::mem;\nuse std::ops::{Deref, DerefMut};\nuse {CommandEncoder, StoreAction, RenderCommandEncoder};\n\n#[derive(Debug)]\npub struct ParallelRenderCommandEncoder(id);\n\nunsafe impl Send for ParallelRenderCommandEncoder {}\n\nimpl Deref for ParallelRenderCommandEncoder {\n type Target = CommandEncoder;\n fn deref(&self) -> &Self::Target {\n unsafe { mem::transmute(&self.0) }\n }\n}\n\nimpl DerefMut for ParallelRenderCommandEncoder {\n fn deref_mut(&mut self) -> &mut Self::Target {\n unsafe { mem::transmute(&mut self.0) }\n }\n}\n\nimpl ParallelRenderCommandEncoder {\n pub fn render_command_encoder(&self) -> RenderCommandEncoder {\n unimplemented!()\n }\n\n pub fn set_color_store_action_at(&self, store_action: StoreAction, index: usize) {\n unimplemented!()\n }\n\n pub fn set_depth_store_action(self, store_action: StoreAction) {\n unimplemented!()\n }\n\n pub fn set_stencil_store_action(self, store_action: StoreAction) {\n unimplemented!()\n }\n}\n\nimpl_from_into_raw!(ParallelRenderCommandEncoder, of protocol \"MTLRenderCommandEncoder\");\n" }, { "from": "gpt", "value": "use cocoa::base::id;\nuse std::mem;\nuse std::ops::{Deref, DerefMut};\nuse {CommandEncoder, StoreAction, RenderCommandEncoder};\n\n#[derive(Debug)]\npub struct ParallelRenderCommandEncoder(id);\n\nunsafe impl Send for ParallelRenderCommandEncoder {}\n\nimpl Deref for ParallelRenderCommandEncoder {\n type Target = CommandEncoder;\n fn deref(&self) -> &Self::Target {\n unsafe { mem::transmute(&self.0) }\n }\n}\n\nimpl DerefMut for ParallelRenderCommandEncoder {\n fn deref_mut(&mut self) -> &mut Self::Target {\n unsafe { mem::transmute(&mut self.0) }\n }\n}\n\nimpl ParallelRenderCommandEncoder {\n pub fn create_render_command_encoder(&self) -> RenderCommandEncoder {\n unimplemented!()\n }\n\n pub fn set_color_store_action_at(&self, store_action: StoreAction, index: usize) {\n unimplemented!()\n }\n\n pub fn set_depth_store_action(self, store_action: StoreAction) {\n unimplemented!()\n }\n\n pub fn set_stencil_store_action(self, store_action: StoreAction) {\n unimplemented!()\n }\n}\n\nimpl_from_into_raw!(ParallelRenderCommandEncoder, of protocol \"MTLRenderCommandEncoder\");\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove line with unimplemented function\n" }, { "from": "human", "value": "extern crate uosql;\n\nuse uosql::storage::*;\n\nfn main() {\n\n //let db = Database::create(\"storage_team\").unwrap();\n let db = Database::load(\"storage_team\").unwrap();\n\n let mut cols = Vec::new();\n cols.push(Column { name: \"Heiner\".into(), data_type: DataType::Integer });\n cols.push(Column { name: \"Mathias\".into(), data_type: DataType::Float });\n cols.push(Column { name: \"Dennis\".into(), data_type: DataType::Float });\n cols.push(Column { name: \"Jana\".into(), data_type: DataType::Integer });\n\n\n let _storage_team = db.create_table(\"storage_team\", cols, 1).unwrap();\n\n let t = db.load_table(\"storage_team\").unwrap();\n\n let mut engine = t.create_engine();\n let _e = engine.create_table();\n let t = engine.get_table();\n}\n" }, { "from": "gpt", "value": "extern crate uosql;\n\nuse uosql::storage::*;\n\nfn main() {\n\n //let db = Database::create(\"storage_team\").unwrap();\n let db = Database::load(\"storage_team\").unwrap();\n\n let mut cols = Vec::new();\n cols.push(Column { name: \"Heiner\".into(), data_type: DataType::Integer });\n cols.push(Column { name: \"Mathias\".into(), data_type: DataType::Float });\n cols.push(Column { name: \"Dennis\".into(), data_type: DataType::Float });\n cols.push(Column { name: \"Jana\".into(), data_type: DataType::Integer });\n\n\n let _storage_team = db.create_table(\"storage_team\", cols, 1).unwrap();\n\n let t = db.load_table(\"storage_team\").unwrap();\n\n let mut engine = t.create_engine();\n let _e = engine.create_table();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Implement Eq and Ord for Rollers\n" }, { "from": "human", "value": "#[macro_use]\nextern crate pest;\nextern crate rand;\n\nmod parse;\nmod random;\n\nuse pest::*;\nuse parse::*;\n\npub fn roll_dice(r: &str) -> i32 {\n let mut parser = Rdp::new(StringInput::new(r));\n parser.expression();\n\n parser.compute()\n}\n\n#[derive(Debug)]\npub struct Roller<'a> {\n roll: &'a str,\n total: i32,\n}\n\nimpl<'a> Roller<'a> {\n pub fn new(roll: &str) -> Roller {\n Roller{\n roll: roll,\n total: roll_dice(roll)\n }\n }\n\n pub fn reroll(&mut self) -> i32 {\n self.total = roll_dice(self.roll);\n\n self.total\n }\n\n pub fn total(&self) -> i32 {\n self.total\n }\n}" }, { "from": "gpt", "value": "#[macro_use]\nextern crate pest;\nextern crate rand;\n\nmod parse;\nmod random;\n\nuse std::cmp::Ordering;\n\nuse pest::*;\nuse parse::*;\n\npub fn roll_dice(r: &str) -> i32 {\n let mut parser = Rdp::new(StringInput::new(r));\n parser.expression();\n\n parser.compute()\n}\n\n#[derive(Debug)]\npub struct Roller<'a> {\n roll: &'a str,\n total: i32,\n}\n\nimpl<'a> Roller<'a> {\n pub fn new(roll: &str) -> Roller {\n Roller{\n roll: roll,\n total: roll_dice(roll)\n }\n }\n\n pub fn reroll(&mut self) -> i32 {\n self.total = roll_dice(self.roll);\n\n self.total\n }\n\n pub fn total(&self) -> i32 {\n self.total\n }\n}\n\nimpl<'a> PartialEq for Roller<'a> {\n fn eq(&self, other: &Roller) -> bool {\n self.total == other.total\n }\n}\n\nimpl<'a> Eq for Roller<'a> {}\n\nimpl<'a> Ord for Roller<'a> {\n fn cmp(&self, other: &Roller) -> Ordering {\n self.total.cmp(&other.total)\n }\n}\n\nimpl<'a> PartialOrd for Roller<'a> {\n fn partial_cmp(&self, other: &Roller) -> Option<Ordering> {\n Some(self.cmp(other))\n }\n}" } ]
rust
chosen
[ { "from": "system", "value": "Remove box syntax feature since it's not used\n" }, { "from": "human", "value": "//! Furry Fiesta is a library for poker.\n//! It's mostly meant for Holdem games, however the core functionality\n//! should work for all game types.\n//!\n//! # Implemented:\n//! Currently Furry Fiesta supports:\n//!\n//! * Hand Iteration.\n//! * Hand Ranking.\n//! * Hand Range parsing.\n//! * Hand Range generation.\n//!\n//! # Planned:\n//! * Holdem Game State.\n//! * Multi-threading\n#![feature(box_syntax, box_patterns)]\n\n/// Allow all the core poker functionality to be used\n/// externally. Everything in core should be agnostic\n/// to poker style.\npub mod core;\n/// The holdem specific code. This contains range\n/// parsing, game state, and starting hand code.\npub mod holdem;\n" }, { "from": "gpt", "value": "//! Furry Fiesta is a library for poker.\n//! It's mostly meant for Holdem games, however the core functionality\n//! should work for all game types.\n//!\n//! # Implemented:\n//! Currently Furry Fiesta supports:\n//!\n//! * Hand Iteration.\n//! * Hand Ranking.\n//! * Hand Range parsing.\n//! * Hand Range generation.\n//!\n//! # Planned:\n//! * Holdem Game State.\n//! * Multi-threading\n\n/// Allow all the core poker functionality to be used\n/// externally. Everything in core should be agnostic\n/// to poker style.\npub mod core;\n/// The holdem specific code. This contains range\n/// parsing, game state, and starting hand code.\npub mod holdem;\n" } ]
rust
chosen
[ { "from": "system", "value": "Rename fps to period, provide more suitable defaults\n" }, { "from": "human", "value": "extern crate rustc_serialize;\nextern crate docopt;\n\nmod display;\nmod world;\n\nuse docopt::Docopt;\nuse std::thread::sleep_ms;\n\nstatic USAGE: &'static str = \"\nUsage:\n golr [options]\n\nOptions:\n -h <height>, --height <height> World height [default: 10]\n -w <width>, --width <width> World width [default: 10]\n -f <fps>, --fps <fps> World fps [default: 33]\n\";\n\n#[derive(RustcDecodable, Debug)]\nstruct CliArgs {\n flag_width: isize,\n flag_height: isize,\n flag_fps: u32,\n}\n\nfn main() {\n let args = Docopt::new(USAGE).and_then(|d| d.decode::<CliArgs>())\n .unwrap_or_else(|e| e.exit());\n\n let mut world = world::World::new(args.flag_width, args.flag_height);\n\n world.randomize();\n\n loop {\n world = world.evolve();\n println!(\"\\x1b[2J\\n{}\", world);\n std::thread::sleep_ms(args.flag_fps);\n }\n}\n" }, { "from": "gpt", "value": "extern crate rustc_serialize;\nextern crate docopt;\n\nmod display;\nmod world;\n\nuse docopt::Docopt;\nuse std::thread::sleep_ms;\n\nstatic USAGE: &'static str = \"\nUsage:\n golr [options]\n\nOptions:\n -h <height>, --height <height> World height, points [default: 25]\n -w <width>, --width <width> World width, points [default: 80]\n -p <period>, --period <period> World generational change period, ms [default: 350]\n\";\n\n#[derive(RustcDecodable, Debug)]\nstruct CliArgs {\n flag_width: isize,\n flag_height: isize,\n flag_period: u32,\n}\n\nfn main() {\n let args = Docopt::new(USAGE).and_then(|d| d.decode::<CliArgs>())\n .unwrap_or_else(|e| e.exit());\n\n let mut world = world::World::new(args.flag_width, args.flag_height);\n\n world.randomize();\n\n loop {\n world = world.evolve();\n println!(\"\\x1b[2J\\n{}\", world);\n std::thread::sleep_ms(args.flag_period);\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Handle Result returned by execute.\n" }, { "from": "human", "value": "use std::io::{self, stdin, stdout, Write};\n\n// TODO(tsion): Use the readline library.\nfn prompt(line: &mut String) -> io::Result<usize> {\n let current_dir = try!(std::env::current_dir());\n print!(\"{}> \", current_dir.display());\n try!(stdout().flush());\n stdin().read_line(line)\n}\n\n#[derive(Clone, Debug)]\nenum Ast {\n Empty,\n Call { command: String, args: Vec<String> }\n}\n\nfn parse(line: &str) -> Ast {\n let mut words = line.split_whitespace();\n\n match words.next() {\n Some(command) => Ast::Call {\n command: String::from(command),\n args: words.map(String::from).collect()\n },\n None => Ast::Empty\n }\n}\n\nfn execute(ast: &Ast) -> io::Result<()> {\n match *ast {\n Ast::Empty => Ok(()),\n Ast::Call { ref command, ref args } => {\n std::process::Command::new(command).args(args).status().map(|_| ())\n },\n }\n}\n\nfn main() {\n let mut line = String::new();\n loop {\n prompt(&mut line).unwrap();\n let ast = parse(&line);\n execute(&ast);\n line.clear();\n }\n}\n" }, { "from": "gpt", "value": "use std::io::{self, stdin, stdout, Write};\n\n// TODO(tsion): Use the readline library.\nfn prompt(line: &mut String) -> io::Result<usize> {\n let current_dir = try!(std::env::current_dir());\n print!(\"{}> \", current_dir.display());\n try!(stdout().flush());\n stdin().read_line(line)\n}\n\n#[derive(Clone, Debug)]\nenum Ast {\n Empty,\n Call { command: String, args: Vec<String> }\n}\n\nfn parse(line: &str) -> Ast {\n let mut words = line.split_whitespace();\n\n match words.next() {\n Some(command) => Ast::Call {\n command: String::from(command),\n args: words.map(String::from).collect()\n },\n None => Ast::Empty\n }\n}\n\nfn execute(ast: &Ast) -> io::Result<()> {\n match *ast {\n Ast::Empty => Ok(()),\n Ast::Call { ref command, ref args } => {\n std::process::Command::new(command).args(args).status().map(|_| ())\n },\n }\n}\n\nfn main() {\n let mut line = String::new();\n loop {\n prompt(&mut line).unwrap();\n let ast = parse(&line);\n execute(&ast).unwrap();\n line.clear();\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add -Wl,-znotext to default linker flags to link with lld 9 on FreeBSD 13.0-CURRENT i386\n\nrust-nightly has been failing to link since 2019-12-10 with variations of\n```\n = note: ld: error: relocation R_386_PC32 cannot be used against symbol __rust_probestack; recompile with -fPIC\n >>> defined in /wrkdirs/usr/ports/lang/rust-nightly/work/rustc-nightly-src/build/i686-unknown-freebsd/stage1/lib/rustlib/i686-unknown-freebsd/lib/libcompiler_builtins-6570a75fe85f0e1a.rlib(compiler_builtins-6570a75fe85f0e1a.compiler_builtins.2i519eqi-cgu.15.rcgu.o)\n >>> referenced by std.4xivr03c-cgu.14\n >>> std-9bd70afd58e204b7.std.4xivr03c-cgu.14.rcgu.o:(_$LT$alloc..boxed..Box$LT$F$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$::call_once::h1c78ed6e734a2bfc (.llvm.10122419023709863394)) in archive /wrkdirs/usr/ports/lang/rust-nightly/work/rustc-nightly-src/build/i686-unknown-freebsd/stage1/lib/rustlib/i686-unknown-freebsd/lib/libstd-9bd70afd58e204b7.rlib\n\n ld: error: relocation R_386_PC32 cannot be used against symbol __rust_probestack; recompile with -fPIC\n >>> defined in /wrkdirs/usr/ports/lang/rust-nightly/work/rustc-nightly-src/build/i686-unknown-freebsd/stage1/lib/rustlib/i686-unknown-freebsd/lib/libcompiler_builtins-6570a75fe85f0e1a.rlib(compiler_builtins-6570a75fe85f0e1a.compiler_builtins.2i519eqi-cgu.15.rcgu.o)\n >>> referenced by std.4xivr03c-cgu.14\n >>> std-9bd70afd58e204b7.std.4xivr03c-cgu.14.rcgu.o:(std::io::util::copy::h9115f048f2203467) in archive /wrkdirs/usr/ports/lang/rust-nightly/work/rustc-nightly-src/build/i686-unknown-freebsd/stage1/lib/rustlib/i686-unknown-freebsd/lib/libstd-9bd70afd58e204b7.rlib\n clang-cpp: error: linker command failed with exit code 1 (use -v to see invocation)\n\nerror: aborting due to previous error\n\nerror: could not compile `rustc_macros`.\n```\nFull log: http://beefy17.nyi.freebsd.org/data/head-i386-default/p523508_s356869/logs/rust-nightly-1.42.0.20200118.log\n\nAFAICT it stopped building after bumping compiler_builtins to 0.1.22\nin https://github.com/rust-lang/rust/pull/67110.\n" }, { "from": "human", "value": "use crate::spec::{LinkerFlavor, Target, TargetResult};\n\npub fn target() -> TargetResult {\n let mut base = super::freebsd_base::opts();\n base.cpu = \"pentium4\".to_string();\n base.max_atomic_width = Some(64);\n base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push(\"-m32\".to_string());\n base.stack_probes = true;\n\n Ok(Target {\n llvm_target: \"i686-unknown-freebsd\".to_string(),\n target_endian: \"little\".to_string(),\n target_pointer_width: \"32\".to_string(),\n target_c_int_width: \"32\".to_string(),\n data_layout: \"e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-\\\n f64:32:64-f80:32-n8:16:32-S128\"\n .to_string(),\n arch: \"x86\".to_string(),\n target_os: \"freebsd\".to_string(),\n target_env: String::new(),\n target_vendor: \"unknown\".to_string(),\n linker_flavor: LinkerFlavor::Gcc,\n options: base,\n })\n}\n" }, { "from": "gpt", "value": "use crate::spec::{LinkerFlavor, Target, TargetResult};\n\npub fn target() -> TargetResult {\n let mut base = super::freebsd_base::opts();\n base.cpu = \"pentium4\".to_string();\n base.max_atomic_width = Some(64);\n let pre_link_args = base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap();\n pre_link_args.push(\"-m32\".to_string());\n pre_link_args.push(\"-Wl,-znotext\".to_string());\n base.stack_probes = true;\n\n Ok(Target {\n llvm_target: \"i686-unknown-freebsd\".to_string(),\n target_endian: \"little\".to_string(),\n target_pointer_width: \"32\".to_string(),\n target_c_int_width: \"32\".to_string(),\n data_layout: \"e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-\\\n f64:32:64-f80:32-n8:16:32-S128\"\n .to_string(),\n arch: \"x86\".to_string(),\n target_os: \"freebsd\".to_string(),\n target_env: String::new(),\n target_vendor: \"unknown\".to_string(),\n linker_flavor: LinkerFlavor::Gcc,\n options: base,\n })\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add basic `BezNode` and `BezQuad`.\n" }, { "from": "gpt", "value": "use std::ops::Index;\nuse std::convert::Into;\n\n#[derive(Debug, Clone, Copy)]\npub enum BezNode {\n Point {\n x: f32,\n y: f32\n },\n\n Control {\n x: f32,\n y: f32\n }\n}\n\nimpl BezNode {\n pub fn x(self) -> f32 {\n <BezNode as Into<(f32, f32)>>::into(self).0\n }\n\n pub fn y(self) -> f32 {\n <BezNode as Into<(f32, f32)>>::into(self).1\n }\n}\n\nimpl Into<[f32; 2]> for BezNode {\n fn into(self) -> [f32; 2] {\n use self::BezNode::*;\n\n match self {\n Point{x, y} |\n Control{x, y} => [x, y]\n }\n }\n}\n\nimpl Into<(f32, f32)> for BezNode {\n fn into(self) -> (f32, f32) {\n use self::BezNode::*;\n\n match self {\n Point{x, y} |\n Control{x, y} => (x, y)\n }\n }\n}\n\npub struct BezQuad<I: Index<usize, Output = BezNode>> {\n array: I\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add ui test with explicit Unpin impl\n" }, { "from": "gpt", "value": "use std::marker::Unpin;\n\n#[cxx::bridge]\nmod ffi {\n extern \"C++\" {\n type Opaque;\n }\n}\n\nimpl Unpin for ffi::Opaque {}\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add tests for Visibility parsing\n\nThese test both general `Visibility` usage, as well as specific failure cases\nfixed by the other two patches in this series.\n" }, { "from": "gpt", "value": "mod features;\n\nuse proc_macro2::TokenStream;\nuse syn::{Result, Visibility};\nuse syn::parse::{Parse, ParseStream};\n\n#[derive(Debug)]\nstruct VisRest {\n vis: Visibility,\n rest: TokenStream,\n}\n\nimpl Parse for VisRest {\n fn parse(input: ParseStream) -> Result<Self> {\n Ok(VisRest {\n vis: input.parse()?,\n rest: input.parse()?,\n })\n }\n}\n\nmacro_rules! assert_vis_parse {\n ($input:expr, Ok($p:pat)) => {\n assert_vis_parse!($input, Ok($p) + \"\");\n };\n\n ($input:expr, Ok($p:pat) + $rest:expr) => {\n let expected = $rest.parse::<TokenStream>().unwrap();\n let parse: VisRest = syn::parse_str($input).unwrap();\n\n match parse.vis {\n $p => {}\n _ => panic!(\"Expected {}, got {:?}\", stringify!($p), parse.vis),\n }\n\n // NOTE: Round-trips through `to_string` to avoid potential whitespace\n // diffs.\n assert_eq!(parse.rest.to_string(), expected.to_string());\n };\n\n ($input:expr, Err) => {\n syn::parse2::<VisRest>($input.parse().unwrap()).unwrap_err();\n };\n}\n\n#[test]\nfn test_pub() {\n assert_vis_parse!(\"pub\", Ok(Visibility::Public(_)));\n}\n\n#[test]\nfn test_crate() {\n assert_vis_parse!(\"crate\", Ok(Visibility::Crate(_)));\n}\n\n#[test]\nfn test_inherited() {\n assert_vis_parse!(\"\", Ok(Visibility::Inherited));\n}\n\n#[test]\nfn test_in() {\n assert_vis_parse!(\"pub(in foo::bar)\", Ok(Visibility::Restricted(_)));\n}\n\n#[test]\nfn test_pub_crate() {\n assert_vis_parse!(\"pub(crate)\", Ok(Visibility::Restricted(_)));\n}\n\n#[test]\nfn test_pub_self() {\n assert_vis_parse!(\"pub(self)\", Ok(Visibility::Restricted(_)));\n}\n\n#[test]\nfn test_pub_super() {\n assert_vis_parse!(\"pub(super)\", Ok(Visibility::Restricted(_)));\n}\n\n#[test]\nfn test_missing_in() {\n assert_vis_parse!(\"pub(foo::bar)\", Ok(Visibility::Public(_)) + \"(foo::bar)\");\n}\n\n#[test]\nfn test_missing_in_path() {\n assert_vis_parse!(\"pub(in)\", Err);\n}\n\n#[test]\nfn test_crate_path() {\n assert_vis_parse!(\"pub(crate::A, crate::B)\", Ok(Visibility::Public(_)) + \"(crate::A, crate::B)\");\n}\n\n#[test]\nfn test_junk_after_in() {\n assert_vis_parse!(\"pub(in some::path @@garbage)\", Err);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a rustdoc test for future rustc_deprecated attributes\n" }, { "from": "gpt", "value": "#![feature(staged_api)]\n\n#![stable(feature = \"rustc_deprecated-future-test\", since = \"1.0.0\")]\n\n// @has rustc_deprecated_future/index.html '//*[@class=\"stab deprecated\"]' \\\n// 'Deprecation planned'\n// @has rustc_deprecated_future/struct.S.html '//*[@class=\"stab deprecated\"]' \\\n// 'Deprecating in 99.99.99: effectively never'\n#[rustc_deprecated(since = \"99.99.99\", reason = \"effectively never\")]\n#[stable(feature = \"rustc_deprecated-future-test\", since = \"1.0.0\")]\npub struct S;\n" } ]
rust
chosen
[ { "from": "human", "value": "Add failure tests for moving out of unboxed closure environments\n" }, { "from": "gpt", "value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(unboxed_closures)]\n\n// Tests that we can't move out of an unboxed closure environment\n// if the upvar is captured by ref or the closure takes self by\n// reference.\n\nfn main() {\n // By-ref cases\n {\n let x = box 0u;\n let f = |&:| drop(x); //~ cannot move\n }\n {\n let x = box 0u;\n let f = |&mut:| drop(x); //~ cannot move\n }\n {\n let x = box 0u;\n let f = |:| drop(x); //~ cannot move\n }\n // By-value cases\n {\n let x = box 0u;\n let f = move |&:| drop(x); //~ cannot move\n }\n {\n let x = box 0u;\n let f = move |&mut:| drop(x); //~ cannot move\n }\n {\n let x = box 0u;\n let f = move |:| drop(x); // this one is ok\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add example for R function call\n" }, { "from": "gpt", "value": "extern crate libr;\n\nuse std::env;\nuse std::ffi::CString;\n\nuse libr::ffi::embedded;\nuse libr::ffi::internals::*;\n\nfn main() {\n if let Err(_) = env::var(\"R_HOME\") {\n panic!(\"Rembedded test need R_HOME be setted\");\n }\n\n let mut s = Box::new(vec![CString::new(\"R\").unwrap().into_raw(),\n CString::new(\"--quiet\").unwrap().into_raw(),\n CString::new(\"--no-save\").unwrap().into_raw()]);\n unsafe {\n embedded::Rf_initEmbeddedR(s.len() as i32, s.as_mut_ptr());\n Rprintf(CString::new(\"Hello world\").unwrap().into_raw());\n embedded::Rf_endEmbeddedR(0);\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add Arc test, triggering an unusual bug.\n\nWeird stuff. Ain't high, ain't drunk, but shit's happening, and it is fucked up. I can smell rainbows.\n" }, { "from": "gpt", "value": "//! This test is a more subtle one. It is one which can hit thread destructors unexpectedly.\n\nextern crate ralloc;\n\nuse std::sync::Arc;\nuse std::thread;\n\nfn main() {\n let numbers: Vec<_> = (0..100).collect();\n let shared_numbers = Arc::new(numbers);\n\n for _ in 0..10 {\n let child_numbers = shared_numbers.clone();\n\n thread::spawn(move || {\n let local_numbers = &child_numbers[..];\n\n // Work with the local numbers\n });\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "testsuite: Add an xfailed test case for the new `extern mod` syntax\n" }, { "from": "gpt", "value": "// Copyright 2013 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n// Just a test that new-style extern mods parse\n\n// xfail-test\nextern mod test = \"github.com/catamorphism/test-pkg\";\n\nfn main() {}" } ]
rust
chosen
[ { "from": "human", "value": "Add Automorphic number in Rust\n" }, { "from": "gpt", "value": "// In mathematics an automorphic number (sometimes referred to as a circular number)\n// is a number whose square \"ends\" in the same digits as the number itself.\n\nfn list_automorphic_numbers(start: i32, end: i32) {\n (start..end)\n .filter(|&n| is_automorphic(n as i128))\n .for_each(|n| println!(\"{}\\t=>\\t{}\", n, n.pow(2)))\n}\n\nfn is_automorphic(n: i128) -> bool {\n let n_str = n.to_string();\n let sq_str = n.pow(2).to_string();\n n_str == sq_str[(sq_str.len() - n_str.len())..]\n}\n\nfn main() {\n list_automorphic_numbers(1, 10000)\n}\n\n#[test]\nfn simple_test() {\n assert!(is_automorphic(5));\n assert!(is_automorphic(6));\n assert!(is_automorphic(76));\n assert!(is_automorphic(376));\n assert!(is_automorphic(890625));\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add rust code for custom-set case\n\nIt passed all test cases\n" }, { "from": "gpt", "value": "use std::collections::HashSet;\nuse std::hash::Hash;\n\n#[derive(Debug, PartialEq)]\npub struct CustomSet<T: Hash + Eq> {\n store: HashSet<T>,\n}\n\nimpl<T> CustomSet<T>\nwhere\n T: Hash + Eq,\n{\n pub fn new(list: Vec<T>) -> CustomSet<T>\n where\n T: Clone,\n {\n CustomSet {\n store: list.iter().cloned().collect(),\n }\n }\n\n pub fn is_empty(&self) -> bool {\n let h = &self.store;\n h.is_empty()\n }\n\n pub fn contains(&self, v: &T) -> bool {\n let h = &self.store;\n h.contains(v)\n }\n\n pub fn add(&mut self, v: T) -> bool {\n let h = &mut self.store;\n h.insert(v)\n }\n\n pub fn is_subset(&self, set: &CustomSet<T>) -> bool {\n let h = &self.store;\n h.is_subset(&set.store)\n }\n\n pub fn is_disjoint(&self, set: &CustomSet<T>) -> bool {\n let h = &self.store;\n h.is_disjoint(&set.store)\n }\n\n pub fn intersection(&self, set: &CustomSet<T>) -> CustomSet<T>\n where\n T: Clone,\n {\n let h = &self.store;\n CustomSet {\n store: h.intersection(&set.store).cloned().collect(),\n }\n }\n\n pub fn difference(&self, set: &CustomSet<T>) -> CustomSet<T>\n where\n T: Clone,\n {\n let h = &self.store;\n CustomSet {\n store: h.difference(&set.store).cloned().collect(),\n }\n }\n\n pub fn union(&self, set: &CustomSet<T>) -> CustomSet<T>\n where\n T: Clone,\n {\n let h = &self.store;\n CustomSet {\n store: h.union(&set.store).cloned().collect(),\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Test that bounds checks are elided for indexing after .[r]position()\n" }, { "from": "gpt", "value": "// min-llvm-version: 11.0.0\n// compile-flags: -O\n// ignore-debug: the debug assertions get in the way\n#![crate_type = \"lib\"]\n\n// Make sure no bounds checks are emitted when slicing or indexing\n// with an index from `position()` or `rposition()`.\n\n// CHECK-LABEL: @position_slice_to_no_bounds_check\n#[no_mangle]\npub fn position_slice_to_no_bounds_check(s: &[u8]) -> &[u8] {\n // CHECK-NOT: panic\n // CHECK-NOT: slice_index_len_fail\n if let Some(idx) = s.iter().position(|b| *b == b'\\\\') {\n &s[..idx]\n } else {\n s\n }\n}\n\n// CHECK-LABEL: @position_slice_from_no_bounds_check\n#[no_mangle]\npub fn position_slice_from_no_bounds_check(s: &[u8]) -> &[u8] {\n // CHECK-NOT: panic\n // CHECK-NOT: slice_index_len_fail\n if let Some(idx) = s.iter().position(|b| *b == b'\\\\') {\n &s[idx..]\n } else {\n s\n }\n}\n\n// CHECK-LABEL: @position_index_no_bounds_check\n#[no_mangle]\npub fn position_index_no_bounds_check(s: &[u8]) -> u8 {\n // CHECK-NOT: panic\n // CHECK-NOT: slice_index_len_fail\n if let Some(idx) = s.iter().position(|b| *b == b'\\\\') {\n s[idx]\n } else {\n 42\n }\n}\n// CHECK-LABEL: @rposition_slice_to_no_bounds_check\n#[no_mangle]\npub fn rposition_slice_to_no_bounds_check(s: &[u8]) -> &[u8] {\n // CHECK-NOT: panic\n // CHECK-NOT: slice_index_len_fail\n if let Some(idx) = s.iter().rposition(|b| *b == b'\\\\') {\n &s[..idx]\n } else {\n s\n }\n}\n\n// CHECK-LABEL: @rposition_slice_from_no_bounds_check\n#[no_mangle]\npub fn rposition_slice_from_no_bounds_check(s: &[u8]) -> &[u8] {\n // CHECK-NOT: panic\n // CHECK-NOT: slice_index_len_fail\n if let Some(idx) = s.iter().rposition(|b| *b == b'\\\\') {\n &s[idx..]\n } else {\n s\n }\n}\n\n// CHECK-LABEL: @rposition_index_no_bounds_check\n#[no_mangle]\npub fn rposition_index_no_bounds_check(s: &[u8]) -> u8 {\n // CHECK-NOT: panic\n // CHECK-NOT: slice_index_len_fail\n if let Some(idx) = s.iter().rposition(|b| *b == b'\\\\') {\n s[idx]\n } else {\n 42\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add a C ABI compatible struct for use when performing\n" }, { "from": "gpt", "value": "static IFNAMSIZ: uint = 16;\nstatic PADDINGSIZE: uint = 22;\nstatic IFF_TAP: u16 = 2;\nstatic IFF_NO_PI: u16 = 0x1000;\n\n\n// An enum representing the possible results of trying to create a tap_ifreq struct\npub enum GetTapDescriptorResult {\n InterfaceNameTooLong,\n InterfaceNameTooShort\n}\n\n\n// A struct to pass to ioctl to create a new tap device. The only elements of the struct required are the name and\n// flags\n#[repr(C)]\npub struct tap_ifreq {\n ifr_name: [u8, ..IFNAMSIZ],\n ifr_flags: u16,\n ifr_padding: [u8, ..PADDINGSIZE]\n}\n\n\nimpl tap_ifreq {\n pub fn new(interface: &str) -> Result<tap_ifreq, GetTapDescriptorResult> {\n match interface.len() {\n 0 => Err(InterfaceNameTooShort),\n\n // We can only accept IFNAMSIZ - 1 bytes, as we need to null-terminate the name\n n @ _ if n >= IFNAMSIZ => Err(InterfaceNameTooLong),\n\n _ => {\n let mut ifreq = tap_ifreq {\n ifr_name: [0, ..IFNAMSIZ],\n ifr_flags: IFF_TAP | IFF_NO_PI,\n ifr_padding: [0, ..PADDINGSIZE]\n };\n\n for (i, byte) in interface.bytes().enumerate() {\n ifreq.ifr_name[i] = byte;\n }\n\n Ok(ifreq)\n }\n }\n }\n}\n\n\n#[cfg(test)]\nmod test {\n use super::{tap_ifreq, InterfaceNameTooLong, InterfaceNameTooShort};\n\n\n #[test]\n fn new_bails_if_interface_len_zero() {\n assert!(match tap_ifreq::new(\"\") {\n Err(InterfaceNameTooShort) => true,\n _ => false\n });\n }\n\n\n #[test]\n fn new_bails_if_interface_len_too_long() {\n assert!(match tap_ifreq::new(\"123456789ABCDEF0\") {\n Err(InterfaceNameTooLong) => true,\n _ => false\n });\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add missing \"max_atomic_width\" to new armv7 android target.\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.features = \"+v7,+thumb2,+vfp3,+d16\".to_string();\n\n Target {\n llvm_target: \"armv7-none-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-i64:64-v128:64:128-a:0:32-n32-S64\".to_string(),\n arch: \"arm\".to_string(),\n target_os: \"android\".to_string(),\n target_env: \"\".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 base.features = \"+v7,+thumb2,+vfp3,+d16\".to_string();\n base.max_atomic_width = 64;\n\n Target {\n llvm_target: \"armv7-none-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-i64:64-v128:64:128-a:0:32-n32-S64\".to_string(),\n arch: \"arm\".to_string(),\n target_os: \"android\".to_string(),\n target_env: \"\".to_string(),\n target_vendor: \"unknown\".to_string(),\n options: base,\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add example for implementing a custom widget\n" }, { "from": "gpt", "value": "extern crate tui;\n\nuse tui::Terminal;\nuse tui::widgets::Widget;\nuse tui::buffer::Buffer;\nuse tui::layout::Rect;\nuse tui::style::Color;\n\nstruct Label<'a> {\n text: &'a str,\n}\n\nimpl<'a> Default for Label<'a> {\n fn default() -> Label<'a> {\n Label { text: \"\" }\n }\n}\n\nimpl<'a> Widget for Label<'a> {\n fn draw(&self, area: &Rect, buf: &mut Buffer) {\n buf.set_string(area.left(),\n area.top(),\n self.text,\n Color::Reset,\n Color::Reset);\n }\n}\n\nimpl<'a> Label<'a> {\n fn text(&mut self, text: &'a str) -> &mut Label<'a> {\n self.text = text;\n self\n }\n}\n\nfn main() {\n let mut terminal = Terminal::new().unwrap();\n terminal.clear();\n Label::default().text(\"Test\").render(&Terminal::size().unwrap(), &mut terminal);\n terminal.finish();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Test that a feature gated cfg variable in a `cfg_attr` on an unconfigured item is allowed\n" }, { "from": "human", "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#![feature(rustc_attrs)]\n\nmacro_rules! mac {\n {} => {\n #[cfg(attr)]\n mod m {\n #[lang_item]\n fn f() {}\n }\n }\n}\n\nmac! {}\n\n#[rustc_error]\nfn main() {} //~ ERROR compilation successful\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#![feature(custom_attribute, rustc_attrs)]\n\nmacro_rules! mac {\n {} => {\n #[cfg(attr)]\n mod m {\n #[lang_item]\n fn f() {}\n\n #[cfg_attr(target_thread_local, custom)]\n fn g() {}\n }\n }\n}\n\nmac! {}\n\n#[rustc_error]\nfn main() {} //~ ERROR compilation successful\n" } ]
rust
chosen
[ { "from": "human", "value": "Add skeleton code for FilterExec.\n" }, { "from": "gpt", "value": "use common::types::Ty;\nuse driver::DriverContext;\nuse super::{Executor, ExecutorFactory};\n\npub struct FilterExecFactory\n{\n\ttypes: Vec<Ty>\n}\n\nimpl FilterExecFactory \n{\n\tpub fn new(f: Box<ExecutorFactory>) -> FilterExecFactory\n\t{\n\t\tFilterExecFactory {\n\t\t\ttypes: Vec::new()\n\t\t}\n\t} \n}\n\nimpl ExecutorFactory for FilterExecFactory\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 FilterExec;\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for compiler reexports removal\n" }, { "from": "gpt", "value": "// compile-flags: --no-defaults\n\n#![crate_name = \"foo\"]\n\n// @has 'foo/index.html' '//code' 'extern crate std;'\n// @!has 'foo/index.html' '//code' 'use std::prelude::v1::*;'\npub struct Foo;\n" } ]
rust
chosen
[ { "from": "human", "value": "[rust] Address of two struct must be different even the struct is empty struct(size is zero).\n" }, { "from": "gpt", "value": "struct EmptyStruct;\n\nfn main() {\n let e1 = EmptyStruct;\n let e2 = EmptyStruct;\n println!(\"{:?}\", &e1 as *const EmptyStruct);\n println!(\"{:?}\", &e2 as *const EmptyStruct);\n\n assert!(&e1 as *const EmptyStruct != &e2 as *const EmptyStruct);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for constant pattern diagnostics\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\nmod foo {\n const b: u8 = 2; //~ NOTE constant defined here\n const d: u8 = 2; //~ NOTE constant defined here\n}\n\nuse foo::b as c; //~ NOTE constant imported here\nuse foo::d; //~ NOTE constant imported here\n\nconst a: u8 = 2; //~ NOTE constant defined here\n\nfn main() {\n let a = 4; //~ ERROR only irrefutable\n //~^ NOTE there already is a constant in scope\n let c = 4; //~ ERROR only irrefutable\n //~^ NOTE there already is a constant in scope\n let d = 4; //~ ERROR only irrefutable\n //~^ NOTE there already is a constant in scope\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "utils: Add tests for the `align_blocks` helper in utils.\n" }, { "from": "gpt", "value": "extern crate clippy_lints;\n\nuse clippy_lints::utils::align_snippets;\n\n#[test]\nfn test_align_snippets_single_line() {\n assert_eq!(\"\", align_snippets(&[\"\"]));\n assert_eq!(\"...\", align_snippets(&[\"...\"]));\n}\n\n#[test]\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn test_align_snippets_multiline() {\n let expected = \"\\\nif condition() {\n do_something();\n do_another_thing();\n yet_another_thing();\n {\n and_then_an_indented_block();\n }\n and_then_something_the_user_indented();\"; // expected\n\n let input = &[\n\"\\\nif condition() {\n do_something();\",\n\" do_another_thing();\",\n\" yet_another_thing();\n {\n and_then_an_indented_block();\n }\n and_then_something_the_user_indented();\",\n ]; // input\n\n let got = align_snippets(input);\n assert_eq!(expected, got);\n\n}\n\n#[test]\n#[cfg_attr(rustfmt, rustfmt_skip)]\nfn test_align_snippets_multiline_with_empty_lines() {\n let expected = \"\\\nif condition() {\n do_something();\n do_another_thing();\n yet_another_thing();\n {\n\n and_then_an_indented_block();\n }\n\n and_then_something_the_user_indented();\"; // expected\n\n let input = &[\n\"\\\nif condition() {\n do_something();\",\n\" do_another_thing();\",\n\" yet_another_thing();\n {\n\n and_then_an_indented_block();\n }\n\n and_then_something_the_user_indented();\",\n ]; // input\n\n let got = align_snippets(input);\n println!(\"Input: {}\\nExpected: {}\\nGot: {}\", input.join(\"\\n\"), &expected, &got);\n assert_eq!(expected, got);\n}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test for `has_test_signature` for explicit return\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// compile-flags: --test\nextern crate test;\n\n#[bench]\nfn bench_explicit_return_type(_: &mut ::test::Bencher) -> () {}\n\n#[test]\nfn test_explicit_return_type() -> () {}\n\n" } ]
rust
chosen
[ { "from": "human", "value": "Add crypto coin ticker lookup functionality\n" }, { "from": "gpt", "value": "use std::io::Read;\n\nuse serde_json;\nuse reqwest;\nuse reqwest::Method;\nuse regex::Regex;\n\nuse ::bot::{Bot, Node, RoomEvent};\n\n\npub struct CryptoCoin {\n}\n\nimpl CryptoCoin {\n pub fn new() -> Self {\n Self {\n }\n }\n}\n\nimpl<'a> Node<'a> for CryptoCoin {\n fn handle(&mut self, bot: &Bot, event: RoomEvent) {\n let revent = &event.raw_event;\n\n if revent.type_ == \"m.room.message\" && revent.content[\"msgtype\"] == \"m.text\" {\n let body = &revent.content[\"body\"].as_str().unwrap();\n\n let re = Regex::new(r\"^p +([A-Za-z]{2,4}) *$\").unwrap();\n\n if let Some(m) = re.captures(body) {\n let ticker = m.get(1).unwrap().as_str().to_uppercase();\n bot.reply(&event, &price_string(&ticker));\n }\n }\n }\n}\n\n\nfn price_string(sym: &str) -> String {\n let spot_price = price(sym, PriceType::Spot);\n if spot_price < 0.0 {\n format!(\"Could not fetch market data for: {}\", sym)\n } else {\n let bid_price = price(sym, PriceType::Bid);\n let ask_price = price(sym, PriceType::Ask);\n\n format!(\"{} - Spot: ${}, Bid/Ask: ${}/{}\",\n sym, spot_price, bid_price, ask_price)\n }\n}\n\n\nfn price(sym: &str, price_type: PriceType) -> f32 {\n let url = format!(\"https://api.coinbase.com/v2/prices/{}-USD/{}\",\n sym, price_type.value());\n\n let client = reqwest::Client::new().unwrap();\n match client.request(Method::Get, &url).unwrap().send() {\n Ok(mut resp) => {\n let mut content = String::new();\n resp.read_to_string(&mut content).unwrap();\n match serde_json::from_str::<CBResponse>(&content) {\n Ok(v) => {\n v.data.amount.parse().unwrap()\n },\n Err(_) => -1.0\n }\n },\n Err(_) => -1.0\n }\n}\n\n\n#[allow(dead_code)]\nenum PriceType {\n Spot,\n Bid,\n Ask,\n}\n\nimpl PriceType {\n fn value(&self) -> &str {\n match *self {\n PriceType::Spot => \"spot\",\n PriceType::Bid => \"sell\",\n PriceType::Ask => \"buy\",\n }\n }\n}\n\n\n// These types are used for deserializing the Coin Base API\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct CBResponse {\n data: Data,\n}\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Data {\n amount: String,\n currency: String,\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add the generic GObject wrapper struct\n" }, { "from": "gpt", "value": "// Copyright 2015, The Rust-GNOME Project Developers.\n// See the COPYRIGHT file at the top-level directory of this distribution.\n// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>\n\nuse std::marker::PhantomData;\nuse glib::object::{Ref, Wrapper};\nuse glib::types::StaticType;\n\npub use glib::object::{Downcast, Upcast};\n\n/// The generic type for `GObject` descendants in GTK.\npub struct Object<T>(Ref, PhantomData<T>);\n\nimpl<T> Wrapper for Object<T>\nwhere Object<T>: StaticType {\n type GlibType = T;\n #[inline]\n unsafe fn wrap(r: Ref) -> Object<T> { Object(r, PhantomData) }\n #[inline]\n fn as_ref(&self) -> &Ref { &self.0 }\n #[inline]\n fn unwrap(self) -> Ref { self.0 }\n}\n\nimpl<T> Clone for Object<T> {\n fn clone(&self) -> Object<T> {\n Object(self.0.clone(), PhantomData)\n }\n}\n\nunsafe impl<T> Upcast<::glib::object::Object> for Object<T> where Object<T>: StaticType { }\n" } ]
rust
chosen
[ { "from": "human", "value": "Add moc test (not testing result)\n" }, { "from": "gpt", "value": "\nextern crate ndarray;\nextern crate ndarray_linalg as linalg;\n\nuse ndarray::prelude::*;\nuse linalg::SquareMatrix;\n\n#[test]\nfn test_eigh() {\n let a = arr2(&[[3.0, 1.0, 1.0], [1.0, 3.0, 1.0], [1.0, 1.0, 3.0]]);\n let (e, vecs) = a.clone().eigh().unwrap();\n println!(\"eigenvalues = \\n{:?}\", e);\n println!(\"V = \\n{:?}\", vecs);\n let av = a.dot(&vecs);\n println!(\"AV = \\n{:?}\", av);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add some simple should_parse tests\n" }, { "from": "gpt", "value": "//! This module contains some simple tests where we can write strings which we \n\nextern crate syn;\n\nmacro_rules! should_parse {\n ($name:ident, { $($in:tt)* }) => {\n #[test]\n fn $name() {\n // Make sure we can parse the file!\n syn::parse_file(stringify!($($in)*)).unwrap();\n }\n }\n}\n\nshould_parse!(generic_associated_type, {\n impl Foo {\n type Item<'a> = &'a i32;\n fn foo<'a>(&'a self) -> Self::Item<'a> {}\n }\n});\n\nshould_parse!(const_generics_use, {\n type X = Foo<5>;\n type Y = Foo<\"foo\">;\n type Z = Foo<X>;\n type W = Foo<{ X + 10 }>;\n});\n" } ]
rust
chosen
[ { "from": "human", "value": "Add test against possible undefined behavior\n" }, { "from": "gpt", "value": "#![cfg(feature = \"std\")]\n\nextern crate rand;\nextern crate libc;\n\nuse rand::{FromEntropy, SmallRng};\nuse rand::distributions::{Distribution, Bernoulli};\n\n#[link_name = \"m\"]\nextern \"C\" {\n fn nextafter(x: f64, y: f64) -> f64;\n}\n\n/// This test should make sure that we don't accidentally have undefined\n/// behavior for large propabilties due to\n/// https://github.com/rust-lang/rust/issues/10184.\n#[test]\nfn large_probability() {\n let p = unsafe { nextafter(1., 0.) };\n assert!(p < 1.);\n let d = Bernoulli::new(p);\n let mut rng = SmallRng::from_entropy();\n for _ in 0..10 {\n assert!(d.sample(&mut rng));\n }\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Test case to make sure typestate checks the body of class constructors\n" }, { "from": "gpt", "value": "// error-pattern:unsatisfied precondition\nclass cat {\n priv {\n let mutable meows : uint;\n }\n\n let how_hungry : int;\n\n fn eat() {\n how_hungry -= 5;\n }\n\n new(in_x : uint, in_y : int) {\n let foo;\n meows = in_x + (in_y as uint);\n how_hungry = foo;\n }\n}\n\nfn main() {\n let nyan : cat = cat(52u, 99);\n nyan.eat();\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add testcase for proper LLVM representation of SIMD types.\n\nTestcase to make sure that no 0-sized padding is inserted in structs and that structs are represented as expected by Neon intrinsics in LLVM.\n" }, { "from": "gpt", "value": "// Make sure that no 0-sized padding is inserted in structs and that\n// structs are represented as expected by Neon intrinsics in LLVM.\n// See #87254.\n\n#![crate_type = \"lib\"]\n#![feature(repr_simd)]\n\n#[derive(Copy, Clone, Debug)]\n#[repr(simd)]\npub struct int16x4_t(pub i16, pub i16, pub i16, pub i16);\n\n#[derive(Copy, Clone, Debug)]\npub struct int16x4x2_t(pub int16x4_t, pub int16x4_t);\n// CHECK: %int16x4x2_t = type { <4 x i16>, <4 x i16> }\n" } ]
rust
chosen
[ { "from": "human", "value": "Add an example with at least 2 arguments\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate structopt;\n\nuse structopt::StructOpt;\n\n#[derive(StructOpt, Debug)]\nstruct Opt {\n #[structopt(raw(required = \"true\", min_values = \"2\"))]\n foos: Vec<String>,\n}\n\nfn main() {\n let opt = Opt::from_args();\n println!(\"{:?}\", opt);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add an example of playing a WAV file.\n\nAddresses #458.\n" }, { "from": "gpt", "value": "extern crate sdl2;\n\nuse sdl2::audio::{AudioCallback, AudioSpecDesired,AudioSpecWAV,AudioCVT};\n\n// NOTE: You probably want to investigate SDL_Mixer\n// (https://github.com/andelf/rust-sdl2_mixer) for real use cases.\n\nstruct Sound {\n data: Vec<u8>,\n volume: f32,\n pos: usize,\n}\n\nimpl AudioCallback for Sound {\n type Channel = u8;\n\n fn callback(&mut self, out: &mut [u8]) {\n for dst in out.iter_mut() {\n *dst = (*self.data.get(self.pos).unwrap_or(&0) as f32 * self.volume) as u8;\n self.pos += 1;\n }\n }\n}\n\nfn main() {\n let sdl_context = sdl2::init().unwrap();\n let audio_subsystem = sdl_context.audio().unwrap();\n\n let desired_spec = AudioSpecDesired {\n freq: Some(44100),\n channels: Some(1), // mono\n samples: None // default\n };\n\n let device = audio_subsystem.open_playback(None, desired_spec, |spec| {\n let wav = AudioSpecWAV::load_wav(\"./tests/sine.wav\")\n .ok()\n .expect(\"Could not load test WAV file\");\n\n let cvt = AudioCVT::new(\n wav.format, wav.channels, wav.freq,\n spec.format, spec.channels, spec.freq)\n .ok()\n .expect(\"Could not convert WAV file\");\n\n let data = cvt.convert(wav.buffer().to_vec());\n\n // initialize the audio callback\n Sound {\n data: data,\n volume: 0.25,\n pos: 0,\n }\n }).unwrap();\n\n // Start playback\n device.resume();\n\n // Play for a second\n std::thread::sleep_ms(1000);\n\n // Device is automatically closed when dropped\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Add Rust code for circular-buffer\n\nIt passed all test cases\n" }, { "from": "gpt", "value": "use std::collections::VecDeque;\n\npub struct CircularBuffer<T> {\n buffer: VecDeque<T>,\n size: usize,\n}\n\n#[derive(Debug, PartialEq)]\npub enum Error {\n EmptyBuffer,\n FullBuffer,\n}\n\nimpl<T> CircularBuffer<T> {\n pub fn new(size: usize) -> Self {\n CircularBuffer {\n buffer: VecDeque::new(),\n size: size,\n }\n }\n\n pub fn read(&mut self) -> Result<T, Error> {\n self.buffer.pop_front().ok_or(Error::EmptyBuffer)\n }\n\n pub fn write(&mut self, v: T) -> Result<usize, Error> {\n if self.buffer.len() == self.size {\n return Err(Error::FullBuffer);\n }\n\n self.buffer.push_back(v);\n\n Ok(self.buffer.len())\n }\n\n pub fn overwrite(&mut self, v: T) {\n if self.buffer.len() == self.size {\n self.buffer.pop_front().unwrap();\n }\n\n self.buffer.push_back(v);\n }\n\n pub fn clear(&mut self) {\n self.buffer.clear()\n }\n}\n" } ]
rust
chosen