conversations
listlengths
2
3
source
stringclasses
1 value
stack
stringclasses
1 value
[ { "from": "system", "value": "Implement to_string as trait in infer_schema/TableData\n" }, { "from": "human", "value": "use std::ops::Deref;\n\nuse quote;\n\n#[derive(Debug, Clone)]\npub struct TableData {\n /// Table name\n name: String,\n /// Schema name\n schema: Option<String>,\n}\n\nimpl TableData {\n pub fn new(name: &str, schema: Option<&str>) -> TableData {\n TableData {\n name: name.into(),\n schema: schema.map(String::from),\n }\n }\n\n pub fn name(&self) -> &String {\n &self.name\n }\n\n pub fn to_string(&self) -> String {\n match self.schema {\n Some(ref schema_name) => format!(\"{}.{}\", schema_name, self.name),\n None => self.name.clone(),\n }\n }\n\n pub fn set_tokens(&self, tokens: quote::Tokens) -> TableDataWithTokens {\n TableDataWithTokens {\n table: self.clone(),\n tokens: tokens,\n }\n }\n}\n\n#[derive(Debug, Clone)]\npub struct TableDataWithTokens {\n /// Table data with name and schema\n table: TableData,\n /// Table represented as tokens of `table!` macro\n tokens: quote::Tokens,\n}\n\nimpl TableDataWithTokens {\n pub fn tokens(&self) -> quote::Tokens {\n self.tokens.clone()\n }\n}\n\nimpl Deref for TableDataWithTokens {\n type Target = TableData;\n\n fn deref(&self) -> &TableData {\n &self.table\n }\n}\n" }, { "from": "gpt", "value": "use std::ops::Deref;\n\nuse quote;\n\n#[derive(Debug, Clone)]\npub struct TableData {\n /// Table name\n name: String,\n /// Schema name\n schema: Option<String>,\n}\n\nimpl TableData {\n pub fn new(name: &str, schema: Option<&str>) -> TableData {\n TableData {\n name: name.into(),\n schema: schema.map(String::from),\n }\n }\n\n pub fn name(&self) -> &String {\n &self.name\n }\n\n pub fn set_tokens(&self, tokens: quote::Tokens) -> TableDataWithTokens {\n TableDataWithTokens {\n table: self.clone(),\n tokens: tokens,\n }\n }\n}\n\nimpl ToString for TableData {\n fn to_string(&self) -> String {\n match self.schema {\n Some(ref schema_name) => format!(\"{}.{}\", schema_name, self.name),\n None => self.name.clone(),\n }\n }\n}\n\n#[derive(Debug, Clone)]\npub struct TableDataWithTokens {\n /// Table data with name and schema\n table: TableData,\n /// Table represented as tokens of `table!` macro\n tokens: quote::Tokens,\n}\n\nimpl TableDataWithTokens {\n pub fn tokens(&self) -> quote::Tokens {\n self.tokens.clone()\n }\n}\n\nimpl Deref for TableDataWithTokens {\n type Target = TableData;\n\n fn deref(&self) -> &TableData {\n &self.table\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make it regression test of issue-77668\n" }, { "from": "human", "value": "#![crate_type = \"lib\"]\n\npub fn bar<P>( // Error won't happen if \"bar\" is not generic\n _baz: P,\n) {\n hide_foo()();\n}\n\nfn hide_foo() -> impl Fn() { // Error won't happen if \"iterate\" hasn't impl Trait or has generics\n foo\n}\n\nfn foo() { // Error won't happen if \"foo\" isn't used in \"iterate\" or has generics\n}\n" }, { "from": "gpt", "value": "// revisions: default miropt\n//[miropt]compile-flags: -Z mir-opt-level=2\n// ~^ This flag is for #77668, it used to be ICE.\n\n#![crate_type = \"lib\"]\n\npub fn bar<P>( // Error won't happen if \"bar\" is not generic\n _baz: P,\n) {\n hide_foo()();\n}\n\nfn hide_foo() -> impl Fn() { // Error won't happen if \"iterate\" hasn't impl Trait or has generics\n foo\n}\n\nfn foo() { // Error won't happen if \"foo\" isn't used in \"iterate\" or has generics\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use clap macros for version and author\n" }, { "from": "human", "value": "extern crate clap;\n\nuse clap::{App, Arg};\n\nfn main() {\n\n let matches = App::new(\"aux2bib\")\n .version(\"0.1.0\")\n .author(\"Nathan Musoke\")\n .about(\"gets BibTeX keys from Inspire\")\n .arg(Arg::with_name(\"INPUT\")\n .help(\"Sets the input file to use\")\n .index(1))\n .arg(Arg::with_name(\"OUTPUT\")\n .help(\"Sets the output file to use\")\n .index(2))\n .get_matches();\n}\n" }, { "from": "gpt", "value": "#[macro_use(crate_version, crate_authors)]\nextern crate clap;\n\nuse clap::{App, Arg};\n\nfn main() {\n\n let matches = App::new(\"aux2bib\")\n .version(crate_version!())\n .author(crate_authors!(\",\\n\"))\n .about(\"gets BibTeX keys from Inspire\")\n .arg(Arg::with_name(\"INPUT\")\n .help(\"Sets the input file to use\")\n .index(1))\n .arg(Arg::with_name(\"OUTPUT\")\n .help(\"Sets the output file to use\")\n .index(2))\n .get_matches();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Replace the hand-crafted array to u64/u32 conversions by the std one\n" }, { "from": "human", "value": "#[inline]\npub(crate) fn u64_to_arr(number: u64) -> [u8; 8] {\n number.to_le_bytes()\n}\n\n#[inline]\npub(crate) fn arr_to_u64(arr: &[u8]) -> u64 {\n debug_assert_eq!(arr.len(), 8);\n u64::from(arr[0])\n + ((u64::from(arr[1])) << 8)\n + ((u64::from(arr[2])) << 16)\n + ((u64::from(arr[3])) << 24)\n + ((u64::from(arr[4])) << 32)\n + ((u64::from(arr[5])) << 40)\n + ((u64::from(arr[6])) << 48)\n + ((u64::from(arr[7])) << 56)\n}\n\n#[inline]\npub(crate) fn arr_to_u32(arr: &[u8]) -> u32 {\n debug_assert_eq!(arr.len(), 4);\n u32::from(arr[0])\n + ((u32::from(arr[1])) << 8)\n + ((u32::from(arr[2])) << 16)\n + ((u32::from(arr[3])) << 24)\n}\n\n#[inline]\npub(crate) fn u32_to_arr(number: u32) -> [u8; 4] {\n number.to_le_bytes()\n}\n" }, { "from": "gpt", "value": "use std::convert::TryInto;\n\n#[inline]\npub(crate) fn u64_to_arr(number: u64) -> [u8; 8] {\n number.to_le_bytes()\n}\n\n#[inline]\npub(crate) fn arr_to_u64(arr: &[u8]) -> u64 {\n arr.try_into().map(u64::from_le_bytes).unwrap()\n}\n\n#[inline]\npub(crate) fn arr_to_u32(arr: &[u8]) -> u32 {\n arr.try_into().map(u32::from_le_bytes).unwrap()\n}\n\n#[inline]\npub(crate) fn u32_to_arr(number: u32) -> [u8; 4] {\n number.to_le_bytes()\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add documentation for Frame fields\n" }, { "from": "human", "value": "/// Maximum number of channels supported in the FLAC format.\npub const MAX_CHANNELS: usize = 8;\n\n/// Audio frame that contains one sample for each channel.\npub struct Frame {\n pub header: Header,\n pub footer: Footer,\n}\n\n/// Channel assignment order.\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum ChannelAssignment {\n Independent = 0,\n LeftSide = 1,\n RightSide = 2,\n MiddleSide = 3,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum NumberType {\n Frame(u32),\n Sample(u64),\n}\n\n/// Information regarding the current audio frame.\n#[derive(Debug, PartialEq, Eq)]\npub struct Header {\n pub block_size: u32,\n pub sample_rate: u32,\n pub channels: u8,\n pub channel_assignment: ChannelAssignment,\n pub bits_per_sample: usize,\n pub number: NumberType,\n pub crc: u8,\n}\n\n/// End of the audio frame.\n///\n/// Contains a value that represents the CRC-16 of everything inside the\n/// frame before the footer.\n#[derive(Debug, PartialEq, Eq)]\npub struct Footer(pub u16);\n" }, { "from": "gpt", "value": "/// Maximum number of channels supported in the FLAC format.\npub const MAX_CHANNELS: usize = 8;\n\n/// Audio frame that contains one sample for each channel.\npub struct Frame {\n /// Information regarding the current audio frame.\n pub header: Header,\n /// CRC-16 of all frame bytes before this footer.\n pub footer: Footer,\n}\n\n/// Channel assignment order.\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum ChannelAssignment {\n Independent = 0,\n LeftSide = 1,\n RightSide = 2,\n MiddleSide = 3,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum NumberType {\n Frame(u32),\n Sample(u64),\n}\n\n/// Information regarding the current audio frame.\n#[derive(Debug, PartialEq, Eq)]\npub struct Header {\n pub block_size: u32,\n pub sample_rate: u32,\n pub channels: u8,\n pub channel_assignment: ChannelAssignment,\n pub bits_per_sample: usize,\n pub number: NumberType,\n pub crc: u8,\n}\n\n/// End of the audio frame.\n///\n/// Contains a value that represents the CRC-16 of everything inside the\n/// frame before the footer.\n#[derive(Debug, PartialEq, Eq)]\npub struct Footer(pub u16);\n" } ]
rust
chosen
[ { "from": "system", "value": "Use a closure for drop odd\n" }, { "from": "human", "value": "extern crate libnfqueue as nfq;\n\nuse nfq::{Handle, ProtocolFamily, CopyMode, VerdictHandler, Message, Verdict};\n\nfn main() {\n let mut handle = Handle::new().ok().unwrap();\n let mut queue = handle.queue(0, Decider{count: 0}).unwrap();\n\n handle.bind(ProtocolFamily::INET).ok();\n queue.mode(CopyMode::Packet(4096)).ok();\n\n println!(\"Listening for packets...\");\n handle.start(4096);\n\n println!(\"Finished...\");\n}\n\nstruct Decider {\n count: i32\n}\n\nimpl VerdictHandler for Decider {\n fn decide(&mut self, message: &mut Message) -> Verdict {\n let id = message.header().id();\n\n self.count += 1;\n if self.count % 2 == 0 {\n println!(\"Accepting packet {}\", id);\n Verdict::Accept\n } else {\n println!(\"Dropping packet {}\", id);\n Verdict::Drop\n }\n }\n}\n" }, { "from": "gpt", "value": "extern crate libnfqueue as nfq;\n\nuse nfq::{Handle, ProtocolFamily, CopyMode, VerdictHandler, Message, Verdict};\n\nfn main() {\n let mut handle = Handle::new().ok().unwrap();\n\n let mut count = 0;\n\n let mut queue = handle.queue(0, move |message: &mut Message| {\n let id = message.header().id();\n\n count += 1;\n\n if count % 2 == 0 {\n println!(\"{} accepting packet\", id);\n Verdict::Accept\n } else {\n println!(\"{} dropping packet\", id);\n Verdict::Drop\n }\n }).unwrap();\n\n handle.bind(ProtocolFamily::INET).ok();\n queue.mode(CopyMode::Packet(4096)).ok();\n\n println!(\"Listening for packets...\");\n handle.start(4096);\n\n println!(\"Finished...\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unused variable and import warnings\n" }, { "from": "human", "value": "use super::schema::notes;\nuse rocket::{Request, Data, Outcome};\nuse rocket::data::{self, FromData};\nuse rocket::http::Status;\nuse rocket::Outcome::*;\nuse serde_json;\nuse rocket_contrib::JSON;\n\n#[derive(Queryable)]\n#[derive(Serialize,Deserialize)]\npub struct Note {\n pub id: i32,\n pub title: String,\n pub body: String,\n pub pinned: bool,\n}\n\n#[derive(Insertable, Deserialize, AsChangeset)]\n#[table_name=\"notes\"]\npub struct NoteData {\n pub title: String,\n pub body: String,\n pub pinned: bool,\n}\n\nimpl FromData for NoteData {\n type Error = String;\n\n fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> {\n let reader = data.open();\n let json_data: JSON<NoteData> = match serde_json::from_reader(reader).map(|val| JSON(val)) {\n Ok(value) => value,\n Err(e) => {\n return Failure((Status::BadRequest, e.to_string()))\n }\n };\n\n Success(NoteData {\n title: json_data.title.to_owned(),\n body: json_data.body.to_owned(),\n pinned: json_data.pinned\n })\n }\n}\n" }, { "from": "gpt", "value": "use super::schema::notes;\nuse rocket::{Request, Data};\nuse rocket::data::{self, FromData};\nuse rocket::http::Status;\nuse rocket::Outcome::*;\nuse serde_json;\nuse rocket_contrib::JSON;\n\n#[derive(Queryable)]\n#[derive(Serialize,Deserialize)]\npub struct Note {\n pub id: i32,\n pub title: String,\n pub body: String,\n pub pinned: bool,\n}\n\n#[derive(Insertable, Deserialize, AsChangeset)]\n#[table_name=\"notes\"]\npub struct NoteData {\n pub title: String,\n pub body: String,\n pub pinned: bool,\n}\n\nimpl FromData for NoteData {\n type Error = String;\n\n #[allow(unused_variables)]\n fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> {\n let reader = data.open();\n let json_data: JSON<NoteData> = match serde_json::from_reader(reader).map(|val| JSON(val)) {\n Ok(value) => value,\n Err(e) => {\n return Failure((Status::BadRequest, e.to_string()))\n }\n };\n\n Success(NoteData {\n title: json_data.title.to_owned(),\n body: json_data.body.to_owned(),\n pinned: json_data.pinned\n })\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Define NotifyNotification directly instead of using a type alias\n" }, { "from": "human", "value": "use gobject::GObject;\nuse libc::c_char;\nuse glib::GError;\n\npub type NotifyNotification = _NotifyNotification;\n\n#[repr(C)]\nstruct NotifyNotificationPrivate;\n\n#[repr(C)]\nstruct _NotifyNotification {\n _parent_object: GObject,\n _priv_: NotifyNotificationPrivate\n}\n\nextern \"C\" {\n pub fn notify_notification_new(summary: *const c_char,\n body: *const c_char,\n icon: *const c_char)\n -> *mut NotifyNotification;\n pub fn notify_notification_show(notification: *mut NotifyNotification,\n error: *mut *mut GError);\n}\n" }, { "from": "gpt", "value": "use gobject::GObject;\nuse libc::c_char;\nuse glib::GError;\n\n#[repr(C)]\nstruct NotifyNotificationPrivate;\n\n#[repr(C)]\npub struct NotifyNotification {\n _parent_object: GObject,\n _priv_: NotifyNotificationPrivate\n}\n\nextern \"C\" {\n pub fn notify_notification_new(summary: *const c_char,\n body: *const c_char,\n icon: *const c_char)\n -> *mut NotifyNotification;\n pub fn notify_notification_show(notification: *mut NotifyNotification,\n error: *mut *mut GError);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Work around rustup fallback error on Windows\n" }, { "from": "human", "value": "#[test]\nfn fmt() {\n if option_env!(\"RUSTC_TEST_SUITE\").is_some() {\n return;\n }\n\n let root_dir = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n let dev_dir = root_dir.join(\"clippy_dev\");\n let output = std::process::Command::new(\"cargo\")\n .current_dir(dev_dir)\n .args(&[\"run\", \"--\", \"fmt\", \"--check\"])\n .output()\n .unwrap();\n\n println!(\"status: {}\", output.status);\n println!(\"stdout: {}\", String::from_utf8_lossy(&output.stdout));\n println!(\"stderr: {}\", String::from_utf8_lossy(&output.stderr));\n\n assert!(\n output.status.success(),\n \"Formatting check failed. Run `./util/dev fmt` to update formatting.\"\n );\n}\n" }, { "from": "gpt", "value": "#[test]\nfn fmt() {\n if option_env!(\"RUSTC_TEST_SUITE\").is_some() {\n return;\n }\n\n let root_dir = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n let dev_dir = root_dir.join(\"clippy_dev\");\n let output = std::process::Command::new(\"cargo\")\n .current_dir(dev_dir)\n .args(&[\"+nightly\", \"run\", \"--\", \"fmt\", \"--check\"])\n .output()\n .unwrap();\n\n println!(\"status: {}\", output.status);\n println!(\"stdout: {}\", String::from_utf8_lossy(&output.stdout));\n println!(\"stderr: {}\", String::from_utf8_lossy(&output.stderr));\n\n assert!(\n output.status.success(),\n \"Formatting check failed. Run `./util/dev fmt` to update formatting.\"\n );\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a new 'mutable' trait to treenode\n" }, { "from": "human", "value": "use super::values::*;\n\n///\n/// The treenode trait is implemented by things that can act as part of a tree\n///\npub trait TreeNode {\n ///\n /// Counts the number of children of this tree node\n ///\n fn count_children(&self) -> u32;\n\n ///\n /// Retrieves the child at the specified index\n ///\n fn get_child(&self, index: u32) -> &TreeNode;\n\n ///\n /// Retrieves the tag attached to this tree node\n ///\n fn get_tag(&self) -> &str;\n\n ///\n /// Retrieves the value attached to this node\n ///\n fn get_value(&self) -> &TreeValue;\n}\n" }, { "from": "gpt", "value": "use super::values::*;\n\n///\n/// The treenode trait is implemented by types that can act as part of a tree\n///\npub trait TreeNode {\n ///\n /// Counts the number of children of this tree node\n ///\n fn count_children(&self) -> u32;\n\n ///\n /// Retrieves the child at the specified index\n ///\n fn get_child(&self, index: u32) -> &TreeNode;\n\n ///\n /// Retrieves the tag attached to this tree node\n ///\n fn get_tag(&self) -> &str;\n\n ///\n /// Retrieves the value attached to this node\n ///\n fn get_value(&self) -> &TreeValue;\n}\n\n///\n/// This trait is implemented by types that can be converted into a tree node.\n///\npub trait ToTreeNode {\n ///\n /// Converts this value into a tree node\n ///\n fn to_tree_node(&self) -> Box<TreeNode>;\n}\n\n///\n/// This trait is implemented by tree nodes that can be changed\n///\npub trait MutableTreeNode : TreeNode {\n ///\n /// Adds a new child node to this node. Returns the same node so many nodes can be altered as part of a single statement.\n ///\n fn add_child(&mut self, newNode: ToTreeNode) -> &MutableTreeNode;\n\n ///\n /// Removes the child node at the specified index. Returns the same node so many nodes can be altered as part of a single statement\n ///\n fn remove_child(&mut self, index: u32) -> &MutableTreeNode;\n\n ///\n /// Changes the value set for this node. Returns the same node so many nodes can be altered as part of a single statement.\n ///\n fn set_value(&mut self, newValue: ToTreeValue) -> &MutableTreeNode;\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "[network] Add documentation for Direct Send Message\n" }, { "from": "human", "value": "// Copyright (c) The Diem Core Contributors\n// SPDX-License-Identifier: Apache-2.0\n\nuse crate::{protocols::network::SerializedRequest, ProtocolId};\nuse bytes::Bytes;\nuse serde::Serialize;\nuse std::fmt::Debug;\n\n// TODO(philiphayes): just use wire::DirectSendMsg directly\n\n#[derive(Clone, Eq, PartialEq, Serialize)]\npub struct Message {\n /// Message type.\n pub protocol_id: ProtocolId,\n /// Serialized message data.\n #[serde(skip)]\n pub mdata: Bytes,\n}\n\nimpl Debug for Message {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n let mdata_str = if self.mdata.len() <= 10 {\n format!(\"{:?}\", self.mdata)\n } else {\n format!(\"{:?}...\", self.mdata.slice(..10))\n };\n write!(\n f,\n \"Message {{ protocol: {:?}, mdata: {} }}\",\n self.protocol_id, mdata_str\n )\n }\n}\n\nimpl SerializedRequest for Message {\n fn protocol_id(&self) -> ProtocolId {\n self.protocol_id\n }\n\n fn data(&self) -> &Bytes {\n &self.mdata\n }\n}\n" }, { "from": "gpt", "value": "// Copyright (c) The Diem Core Contributors\n// SPDX-License-Identifier: Apache-2.0\n\nuse crate::{protocols::network::SerializedRequest, ProtocolId};\nuse bytes::Bytes;\nuse serde::Serialize;\nuse std::fmt::Debug;\n\n#[derive(Clone, Eq, PartialEq, Serialize)]\npub struct Message {\n /// The [`ProtocolId`] for which of our upstream application modules should\n /// handle (i.e., deserialize and then respond to) this inbound rpc request.\n ///\n /// For example, if `protocol_id == ProtocolId::ConsensusRpc`, then this\n /// inbound rpc request will be dispatched to consensus for handling.\n pub protocol_id: ProtocolId,\n /// The serialized request data received from the sender. At this layer in\n /// the stack, the request data is just an opaque blob and will only be fully\n /// deserialized later in the handling application module.\n #[serde(skip)]\n pub mdata: Bytes,\n}\n\nimpl Debug for Message {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n let mdata_str = if self.mdata.len() <= 10 {\n format!(\"{:?}\", self.mdata)\n } else {\n format!(\"{:?}...\", self.mdata.slice(..10))\n };\n write!(\n f,\n \"Message {{ protocol: {:?}, mdata: {} }}\",\n self.protocol_id, mdata_str\n )\n }\n}\n\nimpl SerializedRequest for Message {\n fn protocol_id(&self) -> ProtocolId {\n self.protocol_id\n }\n\n fn data(&self) -> &Bytes {\n &self.mdata\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Change parsing tests to snake case\n" }, { "from": "human", "value": "extern crate lrs;\n\n#[test]\nfn parse_Num() {\n\n}\n\n#[test]\nfn parse_Sym() {\n\n}\n\n#[test]\nfn parse_Atom() {\n\n}\n\n#[test]\nfn parse_List() {\n\n}\n\n#[test]\nfn parse_Expr() {\n\n}\n\n#[test]\nfn parse_Node() {\n\n}\n\n#[test]\nfn parse_Lang() {\n \n}\n" }, { "from": "gpt", "value": "extern crate lrs;\n\n#[test]\nfn parse_num() {\n\n}\n\n#[test]\nfn parse_sym() {\n\n}\n\n#[test]\nfn parse_atom() {\n\n}\n\n#[test]\nfn parse_list() {\n\n}\n\n#[test]\nfn parse_expr() {\n\n}\n\n#[test]\nfn parse_node() {\n\n}\n\n#[test]\nfn parse_lang() {\n\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Define equality, hashing, ordering for Address.\n" }, { "from": "human", "value": "// 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/// The location of something in an address space.\n///\n/// This is used to provide a location of a [`Function`], [`Instruction`],\n/// or other item.\n///\n/// XXX: Should this have any indication for what type of address it is?\n/// An address might be an address within a file, a resolved address\n/// after being loaded, etc.\n///\n/// XXX: Should this include any information about the address space\n/// that it is from?\n///\n/// [`Function`]: struct.Function.html\n/// [`Instruction`]: trait.Instruction.html\n#[derive(Clone,Copy,Debug)]\npub struct Address {\n address: usize,\n}\n\nimpl Address {\n /// Construct an `Address`.\n pub fn new(address: usize) -> Self {\n Address { address: address }\n }\n}\n" }, { "from": "gpt", "value": "// 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/// The location of something in an address space.\n///\n/// This is used to provide a location of a [`Function`], [`Instruction`],\n/// or other item.\n///\n/// XXX: Should this have any indication for what type of address it is?\n/// An address might be an address within a file, a resolved address\n/// after being loaded, etc.\n///\n/// XXX: Should this include any information about the address space\n/// that it is from?\n///\n/// [`Function`]: struct.Function.html\n/// [`Instruction`]: trait.Instruction.html\n#[derive(Clone,Copy,Debug,Eq,Hash,Ord,PartialEq,PartialOrd)]\npub struct Address {\n address: usize,\n}\n\nimpl Address {\n /// Construct an `Address`.\n pub fn new(address: usize) -> Self {\n Address { address: address }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::Address;\n\n #[test]\n fn address_comparison() {\n let addr1 = Address::new(5);\n let addr2 = Address::new(3);\n let addr3 = Address::new(5);\n assert!(addr2 < addr1);\n assert_eq!(addr1, addr3);\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "DummyRenderer: Save last frame of output\n" }, { "from": "human", "value": "//! Dummy frontend that does nothing.\n\nuse frontend_api::{FrontendAction, Renderer, AudioSink};\n\n/// Renderer that just does nothing.\n#[derive(Default)]\npub struct DummyRenderer;\n\nimpl Renderer for DummyRenderer {\n fn render(&mut self, _frame_data: &[u8]) -> Option<FrontendAction> { None }\n fn set_rom_title(&mut self, _title: &str) {}\n}\n\n/// Dummy audio sink with no output\n#[derive(Default)]\npub struct DummySink;\n\nimpl AudioSink for DummySink {\n fn write(&mut self, _data: &[(i16, i16)]) {}\n}\n" }, { "from": "gpt", "value": "//! Dummy frontend that does nothing.\n\nuse frontend_api::{FrontendAction, Renderer, AudioSink};\n\n/// Renderer that just does nothing, apart from saving the PPU output for later use. This allows\n/// users to extract single rendered frames without having to implement `Renderer`.\n#[derive(Default)]\npub struct DummyRenderer {\n last_frame: Vec<u8>,\n}\n\nimpl DummyRenderer {\n pub fn last_frame(&self) -> &[u8] {\n &self.last_frame\n }\n}\n\nimpl Renderer for DummyRenderer {\n fn render(&mut self, frame_data: &[u8]) -> Option<FrontendAction> {\n self.last_frame.clear();\n self.last_frame.extend_from_slice(frame_data);\n None\n }\n\n fn set_rom_title(&mut self, _title: &str) {}\n}\n\n/// Dummy audio sink with no output\n#[derive(Default)]\npub struct DummySink;\n\nimpl AudioSink for DummySink {\n fn write(&mut self, _data: &[(i16, i16)]) {}\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add method to unwrap GcLeaf values.\n\nI tried `impl Into<T> for GcLeaf<T>` but there was some conflict.\n" }, { "from": "human", "value": "use std;\n\n/// GcLeaf can be used to embed just about anything in a GC heap type.\n#[derive(Copy, Clone, Debug, PartialEq)]\npub struct GcLeaf<T: Clone + 'static> {\n // This private field has an underscore in the hopes that it is\n // less likely to collide with useful features of T.\n value_: T,\n}\n\nimpl<T: Clone + 'static> GcLeaf<T> {\n /// Create a new GcLeaf wrapping a given value.\n pub fn new(value: T) -> GcLeaf<T> {\n GcLeaf { value_: value }\n }\n}\n\nimpl<T: Clone + 'static> std::ops::Deref for GcLeaf<T> {\n type Target = T;\n fn deref(&self) -> &T {\n &self.value_\n }\n}\n\nimpl<T: Clone + 'static> std::ops::DerefMut for GcLeaf<T> {\n fn deref_mut(&mut self) -> &mut T {\n &mut self.value_\n }\n}\n" }, { "from": "gpt", "value": "use std;\n\n/// GcLeaf can be used to embed just about anything in a GC heap type.\n#[derive(Copy, Clone, Debug, PartialEq)]\npub struct GcLeaf<T: Clone + 'static> {\n // This private field has an underscore in the hopes that it is\n // less likely to collide with useful features of T.\n value_: T,\n}\n\nimpl<T: Clone + 'static> GcLeaf<T> {\n /// Create a new GcLeaf wrapping a given value.\n pub fn new(value: T) -> GcLeaf<T> {\n GcLeaf { value_: value }\n }\n\n pub fn unwrap(self) -> T {\n self.value_\n }\n}\n\nimpl<T: Clone + 'static> std::ops::Deref for GcLeaf<T> {\n type Target = T;\n fn deref(&self) -> &T {\n &self.value_\n }\n}\n\nimpl<T: Clone + 'static> std::ops::DerefMut for GcLeaf<T> {\n fn deref_mut(&mut self) -> &mut T {\n &mut self.value_\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Switch reporters to using display format\n" }, { "from": "human", "value": "\nuse nom::{Err, Needed};\n\npub fn report_error(err: Err<&[u8], u32>) {\n match err {\n Err::Code(_) => {\n println!(\"Parsing error: Unknown origin\");\n }\n Err::Node(_, n) => {\n println!(\"Parsing error: Unknown origin\");\n for e in n {\n report_error(e);\n }\n }\n Err::Position(_, p) => {\n println!(\n \"Parsing error: When input is {:?}\",\n String::from_utf8_lossy(p).into_owned()\n );\n }\n Err::NodePosition(_, p, n) => {\n println!(\n \"Parsing error: When input is {:?}\",\n String::from_utf8_lossy(p).into_owned()\n );\n for e in n {\n report_error(e);\n }\n }\n }\n}\n\npub fn report_incomplete(needed: Needed, actual: usize) {\n match needed {\n Needed::Unknown => {\n println!(\n \"Data error: insufficient size, expectation unknown, \\\n found {:?} bytes\",\n actual\n );\n }\n Needed::Size(s) => {\n println!(\n \"Data error: insufficient size, expected {:?} bytes \\\n but found {:?}\",\n s,\n actual\n );\n }\n }\n}\n" }, { "from": "gpt", "value": "\nuse nom::{Err, Needed};\n\npub fn report_error(err: Err<&[u8], u32>) {\n match err {\n Err::Code(_) => {\n println!(\"Parsing error: Unknown origin\");\n }\n Err::Node(_, n) => {\n println!(\"Parsing error: Unknown origin\");\n for e in n {\n report_error(e);\n }\n }\n Err::Position(_, p) => {\n println!(\n \"Parsing error: When input is {}\",\n String::from_utf8_lossy(p)\n );\n }\n Err::NodePosition(_, p, n) => {\n println!(\n \"Parsing error: When input is {}\",\n String::from_utf8_lossy(p)\n );\n for e in n {\n report_error(e);\n }\n }\n }\n}\n\npub fn report_incomplete(needed: Needed, actual: usize) {\n match needed {\n Needed::Unknown => {\n println!(\n \"Data error: insufficient size, expectation unknown, \\\n found {} bytes\",\n actual\n );\n }\n Needed::Size(s) => {\n println!(\n \"Data error: insufficient size, expected {} bytes \\\n but found {}\",\n s,\n actual\n );\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Include the note in the test.\n" }, { "from": "human", "value": "struct S {}\n\ntrait T<'a> {\n type A;\n}\n\nimpl T<'_> for S {\n type A = u32;\n}\n\nfn foo(x: impl Fn(<S as T<'_>>::A) -> <S as T<'_>>::A) {}\n//~^ ERROR binding for associated type `Output` references an anonymous lifetime\n\nfn main() {}\n" }, { "from": "gpt", "value": "struct S {}\n\ntrait T<'a> {\n type A;\n}\n\nimpl T<'_> for S {\n type A = u32;\n}\n\nfn foo(x: impl Fn(<S as T<'_>>::A) -> <S as T<'_>>::A) {}\n//~^ ERROR binding for associated type `Output` references an anonymous lifetime\n//~^^ NOTE lifetimes appearing in an associated type are not considered constrained\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Implement converting from fahrenheit to celsius\n" }, { "from": "human", "value": "fn main() {\n println!(\"Hello, world!\");\n}\n" }, { "from": "gpt", "value": "use std::io;\n\nfn main() {\n println!(\"Enter value in Fahrenheit:\");\n\n let mut f = String::new();\n\n io::stdin().read_line(&mut f)\n .expect(\"Failed to read line!\");\n\n let f: f32 = f.trim().parse().expect(\"Enter valid Fahrenheit value!\");\n\n let c = (f - 32.0) * (5.0/9.0);\n\n println!(\"Fahrenheit: {}\", f);\n println!(\"Celsius: {:.2}\", c);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use c_int instead of c_uint to be more inline with termbox\n" }, { "from": "human", "value": "#![feature(libc)]\nextern crate libc;\n\nuse libc::{c_int, c_uint};\n\n#[repr(C)]\n#[derive(Copy)]\npub struct RawEvent {\n pub etype: u8,\n pub emod: u8,\n pub key: u16,\n pub ch: u32,\n pub w: i32,\n pub h: i32,\n pub x: i32,\n pub y: i32,\n}\n\nextern \"C\" {\n pub fn tb_init() -> c_int;\n pub fn tb_shutdown();\n\n pub fn tb_width() -> c_uint;\n pub fn tb_height() -> c_uint;\n\n pub fn tb_clear();\n pub fn tb_present();\n\n pub fn tb_set_cursor(cx: c_int, cy: c_int);\n pub fn tb_change_cell(x: c_uint, y: c_uint, ch: u32, fg: u16, bg: u16);\n\n pub fn tb_select_input_mode(mode: c_int) -> c_int;\n pub fn tb_set_clear_attributes(fg: u16, bg: u16);\n\n pub fn tb_peek_event(ev: *const ::RawEvent, timeout: c_uint) -> c_int;\n pub fn tb_poll_event(ev: *const ::RawEvent) -> c_int;\n}\n" }, { "from": "gpt", "value": "#![feature(libc)]\nextern crate libc;\n\nuse libc::c_int;\n\n#[repr(C)]\n#[derive(Copy)]\npub struct RawEvent {\n pub etype: u8,\n pub emod: u8,\n pub key: u16,\n pub ch: u32,\n pub w: i32,\n pub h: i32,\n pub x: i32,\n pub y: i32,\n}\n\nextern \"C\" {\n pub fn tb_init() -> c_int;\n pub fn tb_shutdown();\n\n pub fn tb_width() -> c_int;\n pub fn tb_height() -> c_int;\n\n pub fn tb_clear();\n pub fn tb_present();\n\n pub fn tb_set_cursor(cx: c_int, cy: c_int);\n pub fn tb_change_cell(x: c_int, y: c_int, ch: u32, fg: u16, bg: u16);\n\n pub fn tb_select_input_mode(mode: c_int) -> c_int;\n pub fn tb_set_clear_attributes(fg: u16, bg: u16);\n\n pub fn tb_peek_event(ev: *const ::RawEvent, timeout: c_int) -> c_int;\n pub fn tb_poll_event(ev: *const ::RawEvent) -> c_int;\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add basic `RefInto` and `MutInto` implementations\n" }, { "from": "human", "value": "pub trait RefInto<'a, T>: MutInto<'a, T> {\n fn ref_into(&'a self) -> T;\n}\n\npub trait MutInto<'a, T> {\n fn mut_into(&'a mut self) -> T;\n}\n" }, { "from": "gpt", "value": "pub trait RefInto<'a, T>: MutInto<'a, T> {\n fn ref_into(&'a self) -> T;\n}\n\npub trait MutInto<'a, T> {\n fn mut_into(&'a mut self) -> T;\n}\n\n\n\nimpl<'a, T: 'a> RefInto<'a, &'a T> for T {\n fn ref_into(&'a self) -> &'a T {\n self\n }\n}\n\nimpl<'a, T: 'a> RefInto<'a, &'a T> for &'a T {\n fn ref_into(&'a self) -> &'a T {\n &**self\n }\n}\n\nimpl<'a, T: 'a> MutInto<'a, &'a T> for T {\n fn mut_into(&'a mut self) -> &'a T {\n self\n }\n}\n\nimpl<'a, T: 'a> MutInto<'a, &'a T> for &'a T {\n fn mut_into(&'a mut self) -> &'a T {\n &**self\n }\n}\n\nimpl<'a, T: 'a> MutInto<'a, &'a T> for &'a mut T {\n fn mut_into(&'a mut self) -> &'a T {\n &**self\n }\n}\n\nimpl<'a, T: 'a> MutInto<'a, &'a mut T> for T {\n fn mut_into(&'a mut self) -> &'a mut T {\n self\n }\n}\n\nimpl<'a, T: 'a> MutInto<'a, &'a mut T> for &'a mut T {\n fn mut_into(&'a mut self) -> &'a mut T {\n &mut **self\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update fuzzer script to previous commit's changes\n" }, { "from": "human", "value": "#![no_main]\n#[macro_use] extern crate libfuzzer_sys;\nextern crate inf_4301a;\n\nuse std::str;\n\nfuzz_target!(|data: &[u8]| {\n\n if let Ok(ref s) = str::from_utf8(data) {\n if let Ok(exprs) = inf_4301a::parse_expressions(&s) {\n if let Err(err) = inf_4301a::do_the_thing(exprs, &mut inf_4301a::env::Environment::new()) {\n inf_4301a::error::print_error(\"<fuzzer>\", &s, err);\n }\n }\n }\n\n});\n" }, { "from": "gpt", "value": "#![no_main]\n#[macro_use] extern crate libfuzzer_sys;\nextern crate inf_4301a;\n\nuse std::str;\n\nfuzz_target!(|data: &[u8]| {\n\n if let Ok(ref s) = str::from_utf8(data) {\n if let Ok(exprs) = inf_4301a::parse_expressions(&s) {\n if let Err(err) = inf_4301a::do_the_thing(exprs, &mut inf_4301a::env::Environment::new()) {\n inf_4301a::error::print_error(\"<fuzzer>\", &s, &err);\n }\n }\n }\n\n});\n" } ]
rust
chosen
[ { "from": "system", "value": "Use imports to shorten lines\n" }, { "from": "human", "value": "extern crate capnpc;\n\nfn main() {\n\n // CAPNP_INCLUDE_DIR=$(shell dirname $(shell which capnp))/../include\n\n let prefix = {\n let output = ::std::process::Command::new(\"which\").arg(\"capnp\")\n .output().unwrap().stdout;\n let path = ::std::path::Path::new(::std::str::from_utf8(&output).unwrap());\n let mut path1 = path.parent().unwrap().parent().unwrap().to_path_buf();\n path1.push(\"include/capnp\");\n path1\n };\n\n ::capnpc::compile(&prefix,\n &[&prefix.clone().join(\"rpc.capnp\"),\n &prefix.join(\"rpc-twoparty.capnp\")]).unwrap();\n}\n" }, { "from": "gpt", "value": "use std::str;\nuse std::path::Path;\nuse std::process::Command;\n\nextern crate capnpc;\n\nfn main() {\n\n // CAPNP_INCLUDE_DIR=$(shell dirname $(shell which capnp))/../include\n\n let prefix = {\n let output = Command::new(\"which\")\n .arg(\"capnp\")\n .output()\n .unwrap().stdout;\n\n let path = Path::new(str::from_utf8(&output).unwrap());\n let mut path1 = path.parent().unwrap().parent().unwrap().to_path_buf();\n path1.push(\"include/capnp\");\n path1\n };\n\n capnpc::compile(&prefix,\n &[&prefix.clone().join(\"rpc.capnp\"),\n &prefix.join(\"rpc-twoparty.capnp\")]).unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add dummy `unimplemented!()` for cocoa api\n" }, { "from": "human", "value": "use {SystrayError};\n\npub struct Window {\n}\n\nimpl Window {\n pub fn new() -> Result<Window, SystrayError> {\n Err(SystrayError::NotImplementedError)\n }\n}\n" }, { "from": "gpt", "value": "use std;\nuse {SystrayError};\n\npub struct Window {\n}\n\nimpl Window {\n pub fn new() -> Result<Window, SystrayError> {\n Err(SystrayError::NotImplementedError)\n }\n pub fn quit(&self) {\n unimplemented!()\n }\n pub fn set_tooltip(&self, _: &String) -> Result<(), SystrayError> {\n unimplemented!()\n }\n pub fn add_menu_item<F>(&self, _: &String, _: F) -> Result<u32, SystrayError>\n where F: std::ops::Fn(&Window) -> () + 'static\n {\n unimplemented!()\n }\n pub fn wait_for_message(&mut self) {\n unimplemented!()\n }\n pub fn set_icon_from_buffer(&self, _: &[u8], _: u32, _: u32) -> Result<(), SystrayError> {\n unimplemented!()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix TODO: Use triple fault to guarantee reboot\n\nCause interrupt, since the IDT is dorked we can't find the INT 3\nhandler (double fault), and the double fault handler can't be\nfound (triple fault).\n" }, { "from": "human", "value": "#[cfg(feature = \"acpi\")]\nuse acpi;\nuse syscall::io::{Io, Pio};\n\n#[no_mangle]\npub unsafe extern fn kreset() -> ! {\n println!(\"kreset\");\n\n // 8042 reset\n {\n println!(\"Reset with 8042\");\n let mut port = Pio::<u8>::new(0x64);\n while port.readf(2) {}\n port.write(0xFE);\n }\n\n // TODO: Use triple fault to guarantee reset\n\n unreachable!();\n}\n\n#[no_mangle]\npub unsafe extern fn kstop() -> ! {\n println!(\"kstop\");\n\n #[cfg(feature = \"acpi\")]\n acpi::set_global_s_state(5);\n\n // Magic shutdown code for bochs and qemu (older versions).\n for c in \"Shutdown\".bytes() {\n let port = 0x8900;\n println!(\"Shutdown with outb(0x{:X}, '{}')\", port, c as char);\n Pio::<u8>::new(port).write(c);\n }\n\n // Magic code for VMWare. Also a hard lock.\n println!(\"Shutdown with cli hlt\");\n asm!(\"cli; hlt\" : : : : \"intel\", \"volatile\");\n\n unreachable!();\n}\n" }, { "from": "gpt", "value": "#[cfg(feature = \"acpi\")]\nuse acpi;\nuse syscall::io::{Io, Pio};\n\n#[no_mangle]\npub unsafe extern fn kreset() -> ! {\n println!(\"kreset\");\n\n // 8042 reset\n {\n println!(\"Reset with 8042\");\n let mut port = Pio::<u8>::new(0x64);\n while port.readf(2) {}\n port.write(0xFE);\n }\n\n // Use triple fault to guarantee reset\n asm!(\"cli\" : : : : \"intel\", \"volatile\");\n asm!(\"lidt cs:0\" : : : : \"intel\", \"volatile\");\n asm!(\"int $$3\" : : : : \"intel\", \"volatile\");\n\n unreachable!();\n}\n\n#[no_mangle]\npub unsafe extern fn kstop() -> ! {\n println!(\"kstop\");\n\n #[cfg(feature = \"acpi\")]\n acpi::set_global_s_state(5);\n\n // Magic shutdown code for bochs and qemu (older versions).\n for c in \"Shutdown\".bytes() {\n let port = 0x8900;\n println!(\"Shutdown with outb(0x{:X}, '{}')\", port, c as char);\n Pio::<u8>::new(port).write(c);\n }\n\n // Magic code for VMWare. Also a hard lock.\n println!(\"Shutdown with cli hlt\");\n asm!(\"cli; hlt\" : : : : \"intel\", \"volatile\");\n\n unreachable!();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "test: Fix a pretty printing test\n\nThe pretty printer handles inlines comments quite badly\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\nextern crate serialize; // {En,De}codable\nextern crate rand; // Rand\n\nmod submod {\n // if any of these are implemented without global calls for any\n // function calls, then being in a submodule will (correctly)\n // cause errors about unrecognised module `std` (or `extra`)\n #[deriving(Eq, Ord, TotalEq, TotalOrd,\n Hash,\n Clone,\n Show, Rand,\n Encodable, Decodable)]\n enum A { A1(uint), A2(int) }\n\n #[deriving(Eq, Ord, TotalEq, TotalOrd,\n Hash,\n Clone,\n Show, Rand,\n Encodable, Decodable)]\n struct B { x: uint, y: int }\n\n #[deriving(Eq, Ord, TotalEq, TotalOrd,\n Hash,\n Clone,\n Show, Rand,\n Encodable, Decodable)]\n struct C(uint, int);\n\n}\n\npub fn main() {}\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\nextern crate serialize;\nextern crate rand;\n\nmod submod {\n // if any of these are implemented without global calls for any\n // function calls, then being in a submodule will (correctly)\n // cause errors about unrecognised module `std` (or `extra`)\n #[deriving(Eq, Ord, TotalEq, TotalOrd,\n Hash,\n Clone,\n Show, Rand,\n Encodable, Decodable)]\n enum A { A1(uint), A2(int) }\n\n #[deriving(Eq, Ord, TotalEq, TotalOrd,\n Hash,\n Clone,\n Show, Rand,\n Encodable, Decodable)]\n struct B { x: uint, y: int }\n\n #[deriving(Eq, Ord, TotalEq, TotalOrd,\n Hash,\n Clone,\n Show, Rand,\n Encodable, Decodable)]\n struct C(uint, int);\n\n}\n\npub fn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Simplify qualification with use statement\n" }, { "from": "human", "value": "mod vm;\nmod command;\nmod parse;\nmod program;\n\nuse vm::VM;\nuse program::Program;\nuse std::io::Write;\nuse std::env;\nuse std::path::Path;\nuse std::fs::File;\nuse std::io::prelude::*;\n\n\nfn main() {\n let vm = VM::new();\n let program = Program::new();\n match env::args().nth(1) {\n None => repl(vm, program),\n Some(arg) => interpreter(arg, vm, program),\n }\n}\n\n\nfn repl (mut vm: VM, mut program: Program) -> () {\n loop {\n print!(\"{}\", if program.is_seeking {\"... \"} else {\"bf> \"});\n std::io::stdout().flush().unwrap();\n\n let mut line = String::new();\n let commands = match std::io::stdin().read_line(&mut line) {\n Ok(0) => break,\n Ok(_) => parse::parse(&line),\n Err(error) => panic!(error),\n };\n program.append(&commands);\n program.execute(&mut vm);\n }\n}\n\n\nfn interpreter(arg: String, mut vm: VM, mut program: Program) -> () {\n let path = Path::new(&arg);\n let mut contents = String::new();\n File::open(&path)\n .unwrap()\n .read_to_string(&mut contents)\n .unwrap();\n\n program.append(&parse::parse(&contents));\n program.execute(&mut vm);\n}\n" }, { "from": "gpt", "value": "mod vm;\nmod command;\nmod parse;\nmod program;\n\nuse vm::VM;\nuse program::Program;\nuse parse::parse;\nuse std::io::Write;\nuse std::env;\nuse std::path::Path;\nuse std::fs::File;\nuse std::io::prelude::*;\n\n\nfn main() {\n let vm = VM::new();\n let program = Program::new();\n match env::args().nth(1) {\n None => repl(vm, program),\n Some(arg) => interpreter(arg, vm, program),\n }\n}\n\n\nfn repl (mut vm: VM, mut program: Program) -> () {\n loop {\n print!(\"{}\", if program.is_seeking {\"... \"} else {\"bf> \"});\n std::io::stdout().flush().unwrap();\n\n let mut line = String::new();\n let commands = match std::io::stdin().read_line(&mut line) {\n Ok(0) => break,\n Ok(_) => parse(&line),\n Err(error) => panic!(error),\n };\n program.append(&commands);\n program.execute(&mut vm);\n }\n}\n\n\nfn interpreter(arg: String, mut vm: VM, mut program: Program) -> () {\n let path = Path::new(&arg);\n let mut contents = String::new();\n File::open(&path)\n .unwrap()\n .read_to_string(&mut contents)\n .unwrap();\n\n program.append(&parse(&contents));\n program.execute(&mut vm);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Refactor trait implementationf or `PortMidiError`\n\n- `Display` implementation was basically the same as `Debug`\n" }, { "from": "human", "value": "use std::fmt::{Display, Formatter, Error as FormatError};\nuse std::error::Error;\n\npub type PortMidiDeviceId = i32;\npub type PortMidiResult<T> = Result<T, PortMidiError>;\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\npub enum PortMidiError {\n HostError,\n InvalidDeviceId,\n InsufficientMemory,\n BufferTooSmall,\n BufferOverflow,\n BadPtr,\n BadData,\n InternalError,\n BufferMaxSize,\n}\nimpl Display for PortMidiError {\n fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> {\n write!(f, \"{:?}\", self)\n }\n}\nimpl Error for PortMidiError {\n fn description(&self) -> &str {\n match *self {\n PortMidiError::HostError => \"Host error\",\n PortMidiError::InvalidDeviceId => \"Invalid device ID\",\n PortMidiError::InsufficientMemory => \"Insufficent memory\",\n PortMidiError::BufferTooSmall => \"Buffer is too small\",\n PortMidiError::BufferOverflow => \"Buffer has overflow\",\n PortMidiError::BadPtr => \"Bad pointer was supplied\",\n PortMidiError::BadData => \"Invalid MIDI message data\",\n PortMidiError::InternalError => \"Portmidi internal error\",\n PortMidiError::BufferMaxSize => \"Buffer cannot be made larger\",\n }\n }\n}\n\n\n" }, { "from": "gpt", "value": "use std::fmt::{Display, Formatter, Error as FormatError};\nuse std::error::Error;\n\npub type PortMidiDeviceId = i32;\npub type PortMidiResult<T> = Result<T, PortMidiError>;\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\npub enum PortMidiError {\n HostError,\n InvalidDeviceId,\n InsufficientMemory,\n BufferTooSmall,\n BufferOverflow,\n BadPtr,\n BadData,\n InternalError,\n BufferMaxSize,\n}\nimpl PortMidiError {\n fn msg(&self) -> &'static str {\n match *self {\n PortMidiError::HostError => \"Host error\",\n PortMidiError::InvalidDeviceId => \"Invalid device ID\",\n PortMidiError::InsufficientMemory => \"Insufficent memory\",\n PortMidiError::BufferTooSmall => \"Buffer is too small\",\n PortMidiError::BufferOverflow => \"Buffer has overflow\",\n PortMidiError::BadPtr => \"Bad pointer was supplied\",\n PortMidiError::BadData => \"Invalid MIDI message data\",\n PortMidiError::InternalError => \"Portmidi internal error\",\n PortMidiError::BufferMaxSize => \"Buffer cannot be made larger\",\n }\n\n }\n}\nimpl Display for PortMidiError {\n fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> {\n write!(f, \"{}\", self.msg())\n }\n}\nimpl Error for PortMidiError {\n fn description(&self) -> &str {\n self.msg()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Update evaluate tool to parse a file\n" }, { "from": "human", "value": "extern crate document;\nextern crate xpath;\n\nuse std::collections::hashmap::HashMap;\n\nuse document::{Document,ToAny};\n\nuse xpath::{XPathEvaluationContext,XPathFactory};\nuse xpath::expression::XPathExpression;\n\nfn main() {\n let mut args = std::os::args();\n\n let arg = match args.remove(1) {\n Some(x) => x,\n None => { println!(\"XPath required\"); return; },\n };\n\n let factory = XPathFactory::new();\n\n let expr = match factory.build(arg.as_slice()) {\n Err(x) => { println!(\"Unable to compile XPath: {}\", x); return; },\n Ok(None) => { println!(\"Unable to compile XPath\"); return; },\n Ok(Some(x)) => x,\n };\n\n let d = Document::new();\n let mut functions = HashMap::new();\n xpath::function::register_core_functions(& mut functions);\n let variables = HashMap::new();\n let mut context = XPathEvaluationContext::new(d.root().to_any(),\n &functions,\n &variables);\n context.next(d.root().to_any());\n\n let res = expr.evaluate(&context);\n\n println!(\"{}\", res);\n}\n" }, { "from": "gpt", "value": "extern crate document;\nextern crate xpath;\n\nuse std::io::File;\n\nuse std::collections::hashmap::HashMap;\n\nuse document::ToAny;\nuse document::parser::Parser;\n\nuse xpath::{XPathEvaluationContext,XPathFactory};\nuse xpath::expression::XPathExpression;\n\nfn main() {\n let mut args = std::os::args();\n\n let filename = match args.remove(1) {\n Some(x) => x,\n None => { println!(\"File required\"); return; },\n };\n\n let xpath_str = match args.remove(1) {\n Some(x) => x,\n None => { println!(\"XPath required\"); return; },\n };\n\n let factory = XPathFactory::new();\n\n let expr = match factory.build(xpath_str.as_slice()) {\n Err(x) => { println!(\"Unable to compile XPath: {}\", x); return; },\n Ok(None) => { println!(\"Unable to compile XPath\"); return; },\n Ok(Some(x)) => x,\n };\n\n let p = Parser::new();\n\n let path = Path::new(filename);\n let mut file = File::open(&path);\n\n let data = match file.read_to_end() {\n Ok(x) => String::from_utf8(x),\n Err(x) => { println!(\"Can't read: {}\", x); return; },\n };\n\n let data = data.ok().expect(\"Unable to convert to UTF-8\");\n\n let d = p.parse(data.as_slice());\n\n let mut functions = HashMap::new();\n xpath::function::register_core_functions(& mut functions);\n let variables = HashMap::new();\n let mut context = XPathEvaluationContext::new(d.root().to_any(),\n &functions,\n &variables);\n context.next(d.root().to_any());\n\n let res = expr.evaluate(&context);\n\n println!(\"{}\", res);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unused extern crate rustc_trans.\n" }, { "from": "human", "value": "#![feature(\n btree_range,\n collections,\n collections_bound,\n question_mark,\n rustc_private,\n pub_restricted,\n)]\n\n// From rustc.\n#[macro_use] extern crate rustc;\nextern crate rustc_borrowck;\nextern crate rustc_data_structures;\nextern crate rustc_mir;\nextern crate rustc_trans;\nextern crate rustc_const_math;\nextern crate syntax;\n#[macro_use] extern crate log;\nextern crate log_settings;\n\n// From crates.io.\nextern crate byteorder;\n\nmod error;\nmod interpreter;\nmod memory;\nmod primval;\n\npub use error::{\n EvalError,\n EvalResult,\n};\n\npub use interpreter::{\n CachedMir,\n EvalContext,\n Frame,\n eval_main,\n run_mir_passes,\n};\n\npub use memory::{\n Memory,\n Pointer,\n AllocId,\n};\n" }, { "from": "gpt", "value": "#![feature(\n btree_range,\n collections,\n collections_bound,\n question_mark,\n rustc_private,\n pub_restricted,\n)]\n\n// From rustc.\n#[macro_use] extern crate rustc;\nextern crate rustc_borrowck;\nextern crate rustc_data_structures;\nextern crate rustc_mir;\nextern crate rustc_const_math;\nextern crate syntax;\n#[macro_use] extern crate log;\nextern crate log_settings;\n\n// From crates.io.\nextern crate byteorder;\n\nmod error;\nmod interpreter;\nmod memory;\nmod primval;\n\npub use error::{\n EvalError,\n EvalResult,\n};\n\npub use interpreter::{\n CachedMir,\n EvalContext,\n Frame,\n eval_main,\n run_mir_passes,\n};\n\npub use memory::{\n Memory,\n Pointer,\n AllocId,\n};\n" } ]
rust
chosen
[ { "from": "system", "value": "Trim down the crate attribute listings\n" }, { "from": "human", "value": "// Copyright 2012-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//! Support code for encoding and decoding types.\n\n/*\nCore encoding and decoding interfaces.\n*/\n\n#![crate_type = \"rlib\"]\n#![crate_type = \"dylib\"]\n#![doc(html_logo_url = \"http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png\",\n html_favicon_url = \"http://www.rust-lang.org/favicon.ico\",\n html_root_url = \"http://doc.rust-lang.org/nightly/\",\n html_playground_url = \"http://play.rust-lang.org/\")]\n#![allow(unknown_features)]\n#![feature(macro_rules, default_type_params, slicing_syntax, globs)]\n\n// test harness access\n#[cfg(test)]\nextern crate test;\n\npub use self::serialize::{Decoder, Encoder, Decodable, Encodable,\n DecoderHelpers, EncoderHelpers};\n\nmod serialize;\nmod collection_impls;\n\npub mod base64;\npub mod hex;\npub mod json;\n" }, { "from": "gpt", "value": "// Copyright 2012-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//! Support code for encoding and decoding types.\n\n#![feature(macro_rules, default_type_params, slicing_syntax, globs)]\n\n// test harness access\n#[cfg(test)]\nextern crate test;\n\npub use self::serialize::{Decoder, Encoder, Decodable, Encodable,\n DecoderHelpers, EncoderHelpers};\n\nmod serialize;\nmod collection_impls;\n\npub mod base64;\npub mod hex;\npub mod json;\n" } ]
rust
chosen
[ { "from": "system", "value": "Add serialize implementation for u64\n" }, { "from": "human", "value": "use std::io;\n\nuse tag;\nuse err;\nuse serial;\n\nimpl serial::traits::Asn1Info for u64 {\n fn asn1_type(&self) -> tag::Type {\n tag::Type::from(\"INTEGER\")\n }\n\n fn asn1_class(&self) -> tag::Class {\n tag::Class::Universal\n }\n\n fn asn1_tagnum(&self) -> tag::TagNum {\n tag::TagNum::from(2u8)\n }\n\n fn asn1_constructed(&self) -> bool {\n false\n }\n}\n\nimpl serial::traits::Asn1Serialize for u64 {\n fn serialize<W: io::Write>(&self, writer: &mut W) -> Result<(), err::EncodeError> {\n unimplemented!();\n }\n}\n\nimpl serial::traits::Asn1Deserialize for u64 {\n fn deserialize<I: Iterator<Item=io::Result<u8>>>(reader: I) -> Result<Self, err::DecodeError> {\n unimplemented!();\n }\n}\n" }, { "from": "gpt", "value": "use std::io;\n\nuse tag;\nuse err;\nuse serial;\nuse byte::write_byte;\n\nimpl serial::traits::Asn1Info for u64 {\n fn asn1_type(&self) -> tag::Type {\n tag::Type::from(\"INTEGER\")\n }\n\n fn asn1_class(&self) -> tag::Class {\n tag::Class::Universal\n }\n\n fn asn1_tagnum(&self) -> tag::TagNum {\n tag::TagNum::from(2u8)\n }\n\n fn asn1_constructed(&self) -> bool {\n false\n }\n}\n\nimpl serial::traits::Asn1Serialize for u64 {\n fn serialize<W: io::Write>(&self, writer: &mut W) -> Result<(), err::EncodeError> {\n let mut started = false;\n // Loop through bytes in int backwards, start writing when first non-zero byte is encounted.\n for offset in (0..8).rev() {\n let shifted: u64 = self >> (offset * 8);\n let byte: u8 = (shifted & 0xff) as u8;\n if !started {\n if byte == 0 {\n continue;\n }\n started = true;\n }\n try!(write_byte(writer, byte));\n }\n\n // If we haven't written anything, write a zero byte.\n if !started {\n try!(write_byte(writer, 0 as u8));\n }\n Ok(())\n }\n}\n\nimpl serial::traits::Asn1Deserialize for u64 {\n fn deserialize<I: Iterator<Item=io::Result<u8>>>(reader: I) -> Result<Self, err::DecodeError> {\n unimplemented!();\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix gl exports in certain circumstances\n" }, { "from": "human", "value": "extern crate gl as gl_lib;\n\nmod context;\n\npub use gl_lib as gl;\npub use context::Context;\n" }, { "from": "gpt", "value": "extern crate gl as gl_lib;\n\nmod context;\n\npub mod gl {\n pub use super::gl_lib::*;\n}\n\npub use context::Context;\n" } ]
rust
chosen
[ { "from": "system", "value": "Make dummy font implementation conform to API changes.\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\nuse string_cache::Atom;\nuse webrender_traits::NativeFontHandle;\n\n#[derive(Deserialize, Serialize, Debug)]\npub struct FontTemplateData {\n pub bytes: Vec<u8>,\n pub identifier: Atom,\n}\n\nimpl FontTemplateData {\n pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData {\n let bytes = match font_data {\n Some(bytes) => {\n bytes\n },\n None => {\n unimplemented!()\n }\n };\n\n FontTemplateData {\n bytes: bytes,\n identifier: identifier,\n }\n }\n pub fn bytes(&self) -> Vec<u8> {\n self.bytes.clone()\n }\n pub fn bytes_if_in_memory(&self) -> Option<Vec<u8>> {\n Some(self.bytes())\n }\n pub fn native_font(&self) -> Option<NativeFontHandle> {\n None\n }\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::io::Error;\nuse string_cache::Atom;\nuse webrender_traits::NativeFontHandle;\n\n#[derive(Deserialize, Serialize, Debug)]\npub struct FontTemplateData {\n pub bytes: Vec<u8>,\n pub identifier: Atom,\n}\n\nimpl FontTemplateData {\n pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> Result<FontTemplateData, Error> {\n let bytes = match font_data {\n Some(bytes) => {\n bytes\n },\n None => {\n unimplemented!()\n }\n };\n\n Ok(FontTemplateData {\n bytes: bytes,\n identifier: identifier,\n })\n }\n pub fn bytes(&self) -> Vec<u8> {\n self.bytes.clone()\n }\n pub fn bytes_if_in_memory(&self) -> Option<Vec<u8>> {\n Some(self.bytes())\n }\n pub fn native_font(&self) -> Option<NativeFontHandle> {\n None\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use a proper protocol definition instead of the already-expanded code.\n" }, { "from": "human", "value": "// Generated from pipe compiler\nmod stream {\n fn init<T: send>() -> (client::stream<T>, server::stream<T>) {\n pipes::entangle()\n }\n enum stream<T: send> { send(T, server::stream<T>), }\n mod client {\n fn send<T: send>(+pipe: stream<T>, +x_0: T) -> stream<T> {\n {\n let (c, s) = pipes::entangle();\n let message = stream::send(x_0, s);\n pipes::send(pipe, message);\n c\n }\n }\n type stream<T: send> = pipes::send_packet<stream::stream<T>>;\n }\n mod server {\n type stream<T: send> = pipes::recv_packet<stream::stream<T>>;\n }\n}\n\nfn main() {\n let (bc, _bp) = stream::init();\n\n stream::client::send(bc, ~\"abc\");\n}\n" }, { "from": "gpt", "value": "proto! stream {\n stream:send<T:send> {\n send(T) -> stream<T>\n }\n}\n\nfn main() {\n let (bc, _bp) = stream::init();\n\n stream::client::send(bc, ~\"abc\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add error banner when running test suite without nightly compiler\n" }, { "from": "human", "value": "// Copyright 2017 Serde Developers\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" }, { "from": "gpt", "value": "// Copyright 2017 Serde Developers\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(/*=============================================]\n#![=== Serde test suite requires a nightly compiler. ===]\n#![====================================================*/)]\n" } ]
rust
chosen
[ { "from": "system", "value": "[sup,core] Set optional PATH when shelling out for ip & hostname.\n\nThis fixes an issue we are seeing in the Supervisor when the default\nbind address is being determined. In minimal environments (such as in a\nStudio, in a Docker container, etc) the `ip` and `hostname` commands may\nnot be found in the `PATH` passed to `hap-sup` on start. The supervisor\ndoes have a runtime dependency on `core/busybox-static` and that\npackage's `PATH` is added to the process' `PATH` just before the\nsupervised service is started. The issue here was that the command line\nparsing/default logic happens way before the service package is\ninstalled and started.\n\nIn an effort to keep things reasonably generic (as these are `util::sys`\nfunctions), the `ip()` and `hostname()` functions optionally take a\n`PATH` value as a `&str` which, if present, is set as the spawned\ncommand's `PATH`. We set a `PATH` for the command line parsing call by\nusing the already-present `busybox_paths()` utility function, and we use\nthe existing `PATH` of the process for all other calls as they happen\nafter the `PATH`-setting logic has executed in `command::start`.\n\nFor example, running the following in the devshell will ensure that the\nUbuntu `iproute2` package's `/sbin/ip` and `/bin/ip` will *not* be found\nor used:\n\n```\n> rm -f /sbin/ip /bin/ip\n\n> hash -r\n\n> command -v ip || echo 'all gone'\nall gone\n\n> env RUST_LOG=err,habitat_core::util::sys=debug hab-sup start core/redis\nDEBUG:habitat_core::util::sys: Shelling out to determine IP address\nDEBUG:habitat_core::util::sys: Setting shell out PATH=/hab/pkgs/core/busybox-static/1.24.2/20160427212720/bin\nDEBUG:habitat_core::util::sys: IP address is 172.17.0.2\nhab-sup(MN): Starting core/redis\nDEBUG:habitat_core::util::sys: Shelling out to determine IP address\nDEBUG:habitat_core::util::sys: IP address is 172.17.0.2\nhab-sup(GS): Supervisor 172.17.0.2: 5e09deec-3a9b-4ccc-8a1f-d7c2d9f70266\nhab-sup(GS): Census redis.default: da58e70a-53a6-4419-a627-ee1d3b6e78d7\nhab-sup(GS): Starting inbound gossip listener\nhab-sup(GS): Starting outbound gossip distributor\nhab-sup(GS): Starting gossip failure detector\nhab-sup(CN): Starting census health adjuster\nDEBUG:habitat_core::util::sys: Shelling out to determine IP address\nDEBUG:habitat_core::util::sys: IP address is 172.17.0.2\nhab-sup(SC): Updated redis.config\nhab-sup(TP): Restarting because the service config was updated via the census\nredis(SV): Starting\n-- snip --\n```\n\nSigned-off-by: Fletcher Nichol <fnichol@nichol.ca>\n\nPull request: #617\nApproved by: fnichol\n" }, { "from": "human", "value": "// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers\n//\n// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.\n// and the party accessing this file (\"Licensee\") apply to Licensee's use of\n// the Software until such time that the Software is made available under an\n// open source license such as the Apache 2.0 License.\n\nuse error::{Error, Result};\nuse std::process::Command;\n\npub fn ip() -> Result<String> {\n debug!(\"Shelling out to determine IP address\");\n let output = try!(Command::new(\"sh\")\n .arg(\"-c\")\n .arg(\"ip route get 8.8.8.8 | awk '{printf \\\"%s\\\", $NF; exit}'\")\n .output());\n match output.status.success() {\n true => {\n debug!(\"IP address is {}\", String::from_utf8_lossy(&output.stdout));\n let ip = try!(String::from_utf8(output.stdout));\n Ok(ip)\n }\n false => {\n debug!(\"IP address command returned: OUT: {} ERR: {}\",\n String::from_utf8_lossy(&output.stdout),\n String::from_utf8_lossy(&output.stderr));\n Err(Error::NoOutboundAddr)\n }\n }\n}\n" }, { "from": "gpt", "value": "// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers\n//\n// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.\n// and the party accessing this file (\"Licensee\") apply to Licensee's use of\n// the Software until such time that the Software is made available under an\n// open source license such as the Apache 2.0 License.\n\nuse error::{Error, Result};\nuse std::process::Command;\n\npub fn ip(path: Option<&str>) -> Result<String> {\n debug!(\"Shelling out to determine IP address\");\n let mut cmd = Command::new(\"sh\");\n cmd.arg(\"-c\").arg(\"ip route get 8.8.8.8 | awk '{printf \\\"%s\\\", $NF; exit}'\");\n if let Some(path) = path {\n cmd.env(\"PATH\", path);\n debug!(\"Setting shell out PATH={}\", path);\n }\n let output = try!(cmd.output());\n match output.status.success() {\n true => {\n debug!(\"IP address is {}\", String::from_utf8_lossy(&output.stdout));\n let ip = try!(String::from_utf8(output.stdout));\n Ok(ip)\n }\n false => {\n debug!(\"IP address command returned: OUT: {} ERR: {}\",\n String::from_utf8_lossy(&output.stdout),\n String::from_utf8_lossy(&output.stderr));\n Err(Error::NoOutboundAddr)\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Implement deref for Buffered wrapper\n" }, { "from": "human", "value": "//! Tools for wrapping devices.\n\nuse types::{AudioDevice, Sample, Time};\n\n\n/// Bundles an AudioDevice with allocated input and output buffers.\n///\n/// To use the device, input samples must first be manually dropped into the\n/// `inputs` buffer, then `tick` may be called to generate outputs. The output\n/// samples can be found in the `outputs` buffer.\npub struct Buffered<D> where D: AudioDevice {\n /// The AudioDevice being wrapped\n pub device: D,\n /// The input buffer\n pub inputs: Vec<Sample>,\n /// The output buffer\n pub outputs: Vec<Sample>,\n}\n\nimpl<D> Buffered<D> where D: AudioDevice {\n /// Calls the device's tick method using the wrapper's buffers.\n pub fn tick(&mut self, t: Time) {\n self.device.tick(t, &self.inputs, &mut self.outputs);\n }\n}\n\nimpl<D> From<D> for Buffered<D> where D: AudioDevice {\n fn from(device: D) -> Self {\n let inputs = device.num_inputs();\n let outputs = device.num_outputs();\n Buffered {\n device: device,\n inputs: vec![0.0; inputs],\n outputs: vec![0.0; outputs],\n }\n }\n}\n" }, { "from": "gpt", "value": "//! Tools for wrapping devices.\n\nuse std::ops::{Deref, DerefMut};\n\nuse types::{AudioDevice, Sample, Time};\n\n\n/// Bundles an AudioDevice with allocated input and output buffers.\n///\n/// To use the device, input samples must first be manually dropped into the\n/// `inputs` buffer, then `tick` may be called to generate outputs. The output\n/// samples can be found in the `outputs` buffer.\npub struct Buffered<D> where D: AudioDevice {\n /// The AudioDevice being wrapped\n pub device: D,\n /// The input buffer\n pub inputs: Vec<Sample>,\n /// The output buffer\n pub outputs: Vec<Sample>,\n}\n\nimpl<D> Buffered<D> where D: AudioDevice {\n /// Calls the device's tick method using the wrapper's buffers.\n pub fn tick(&mut self, t: Time) {\n self.device.tick(t, &self.inputs, &mut self.outputs);\n }\n}\n\nimpl<D> From<D> for Buffered<D> where D: AudioDevice {\n fn from(device: D) -> Self {\n let inputs = device.num_inputs();\n let outputs = device.num_outputs();\n Buffered {\n device: device,\n inputs: vec![0.0; inputs],\n outputs: vec![0.0; outputs],\n }\n }\n}\n\nimpl<D> Deref for Buffered<D> where D: AudioDevice {\n type Target = D;\n fn deref(&self) -> &D {\n &self.device\n }\n}\nimpl<D> DerefMut for Buffered<D> where D: AudioDevice {\n fn deref_mut(&mut self) -> &mut D {\n &mut self.device\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Revert \"Add Sized trait to ElementType\"\n\nThis reverts commit db23b9ec7387b6b5e7caf880e5ef95eb49789a45.\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 + 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" }, { "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 {}\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": "Fix struct syntax for empty struct\n\n* MainState in flappy example\n" }, { "from": "human", "value": "extern crate ggez;\n\nuse ggez::{Game, State, GameError};\nuse std::time::Duration;\n\nstruct MainState\n{\n}\n\nimpl State for MainState\n{\n fn init(&mut self) -> Result<(), GameError>\n {\n println!(\"init\");\n Ok(())\n }\n fn update(&mut self, dt: Duration) -> Result<(), GameError>\n {\n println!(\"update\");\n Ok(())\n }\n fn draw(&mut self) -> Result<(), GameError>\n {\n println!(\"draw\");\n Ok(())\n }\n}\n\npub fn main() {\n let mut g: MainState = MainState {};\n let mut e: Game = Game::new(g);\n e.run();\n}\n" }, { "from": "gpt", "value": "extern crate ggez;\n\nuse ggez::{Game, State, GameError};\nuse std::time::Duration;\n\nstruct MainState;\n\nimpl State for MainState\n{\n fn init(&mut self) -> Result<(), GameError>\n {\n println!(\"init\");\n Ok(())\n }\n fn update(&mut self, dt: Duration) -> Result<(), GameError>\n {\n println!(\"update\");\n Ok(())\n }\n fn draw(&mut self) -> Result<(), GameError>\n {\n println!(\"draw\");\n Ok(())\n }\n}\n\npub fn main() {\n let mut g: MainState = MainState;\n let mut e: Game = Game::new(g);\n e.run();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add trait implementation for SubAssign\n" }, { "from": "human", "value": "use std::ops::{Add, AddAssign, Sub};\n\n#[derive(Debug, Copy, Clone)]\npub struct Vec3 {\n pub i : f64,\n pub j : f64,\n pub k : f64,\n}\n\nimpl Vec3 {\n pub fn length(&self) -> f64 {\n (self.i * self.i + self.j * self.j + self.k * self.k).sqrt()\n }\n}\n\nimpl Add for Vec3 {\n type Output = Vec3;\n fn add(self, other: Vec3) -> Vec3 {\n Vec3 {i: self.i + other.i, j: self.j + other.j, k: self.k + other.k}\n }\n}\n\nimpl AddAssign for Vec3 {\n fn add_assign(&mut self, other: Vec3) {\n *self = Vec3 {\n i: self.i + other.i,\n j: self.j + other.j,\n k: self.k + other.k,\n };\n }\n}\n\nimpl Sub for Vec3 {\n type Output = Vec3;\n fn sub(self, other: Vec3) -> Vec3 {\n Vec3 {i: self.i - other.i, j: self.j - other.j, k: self.k - other.k}\n }\n}\n" }, { "from": "gpt", "value": "use std::ops::{Add, AddAssign, Sub, SubAssign};\n\n#[derive(Debug, Copy, Clone)]\npub struct Vec3 {\n pub i : f64,\n pub j : f64,\n pub k : f64,\n}\n\nimpl Vec3 {\n pub fn length(&self) -> f64 {\n (self.i * self.i + self.j * self.j + self.k * self.k).sqrt()\n }\n}\n\nimpl Add for Vec3 {\n type Output = Vec3;\n fn add(self, other: Vec3) -> Vec3 {\n Vec3 {i: self.i + other.i, j: self.j + other.j, k: self.k + other.k}\n }\n}\n\nimpl AddAssign for Vec3 {\n fn add_assign(&mut self, other: Vec3) {\n *self = Vec3 {\n i: self.i + other.i,\n j: self.j + other.j,\n k: self.k + other.k,\n };\n }\n}\n\nimpl Sub for Vec3 {\n type Output = Vec3;\n fn sub(self, other: Vec3) -> Vec3 {\n Vec3 {i: self.i - other.i, j: self.j - other.j, k: self.k - other.k}\n }\n}\n\nimpl SubAssign for Vec3 {\n fn sub_assign(&mut self, other: Vec3) {\n *self = Vec3 {\n i: self.i - other.i,\n j: self.j - other.j,\n k: self.k - other.k,\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix unused attribute warning regarding the license attribute\n" }, { "from": "human", "value": "// 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#![license = \"MIT/ASL2\"]\n#![crate_name = \"rust-crypto\"]\n\n#![feature(asm)]\n#![feature(macro_rules)]\n#![feature(simd)]\n#![feature(slicing_syntax)]\n\nextern crate serialize;\nextern crate time;\n#[cfg(test)] extern crate test;\n\npub mod aes;\npub mod aessafe;\npub mod bcrypt;\npub mod bcrypt_pbkdf;\npub mod blake2b;\npub mod blockmodes;\npub mod blowfish;\npub mod buffer;\npub mod chacha20;\nmod cryptoutil;\npub mod digest;\npub mod fortuna;\npub mod ghash;\npub mod hmac;\npub mod mac;\npub mod md5;\npub mod pbkdf2;\npub mod poly1305;\npub mod rc4;\npub mod ripemd160;\npub mod salsa20;\npub mod scrypt;\npub mod sha1;\npub mod sha2;\npub mod symmetriccipher;\npub mod util;\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\npub mod aesni;\n" }, { "from": "gpt", "value": "// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![crate_name = \"rust-crypto\"]\n\n#![feature(asm)]\n#![feature(macro_rules)]\n#![feature(simd)]\n#![feature(slicing_syntax)]\n\nextern crate serialize;\nextern crate time;\n#[cfg(test)] extern crate test;\n\npub mod aes;\npub mod aessafe;\npub mod bcrypt;\npub mod bcrypt_pbkdf;\npub mod blake2b;\npub mod blockmodes;\npub mod blowfish;\npub mod buffer;\npub mod chacha20;\nmod cryptoutil;\npub mod digest;\npub mod fortuna;\npub mod ghash;\npub mod hmac;\npub mod mac;\npub mod md5;\npub mod pbkdf2;\npub mod poly1305;\npub mod rc4;\npub mod ripemd160;\npub mod salsa20;\npub mod scrypt;\npub mod sha1;\npub mod sha2;\npub mod symmetriccipher;\npub mod util;\n\n#[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))]\npub mod aesni;\n" } ]
rust
chosen
[ { "from": "system", "value": "[opentitantool] Fix typo in CW310 backend\n\nSigned-off-by: Jorge Prendes <e1833ed3bb567a7d246d72b65c4144d1037bd875@gmail.com>\n" }, { "from": "human", "value": "// Copyright lowRISC contributors.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\nuse anyhow::Result;\nuse structopt::StructOpt;\n\nuse crate::backend::BackendOpts;\nuse crate::transport::cw310::CW310;\nuse crate::transport::Transport;\n\n#[derive(Debug, StructOpt)]\npub struct Cw310Opts {\n #[structopt(\n long,\n help = \"Comma-separated list of CW310 UARTs for non-udev environments. List the console uart first.\"\n )]\n pub cw310_uarts: Option<String>,\n}\n\npub fn create(args: &BackendOpts) -> Result<Box<dyn Transport>> {\n let uarts = args\n .cw310_opts\n .cw310_uarts\n .as_ref()\n .map(|v| v.split(',').collect::<Vec<&str>>())\n .unwrap_or(Vec::new());\n Ok(Box::new(CW310::new(\n args.usb_vid,\n args.usb_vid,\n args.usb_serial.as_deref(),\n &uarts,\n )?))\n}\n" }, { "from": "gpt", "value": "// Copyright lowRISC contributors.\n// Licensed under the Apache License, Version 2.0, see LICENSE for details.\n// SPDX-License-Identifier: Apache-2.0\n\nuse anyhow::Result;\nuse structopt::StructOpt;\n\nuse crate::backend::BackendOpts;\nuse crate::transport::cw310::CW310;\nuse crate::transport::Transport;\n\n#[derive(Debug, StructOpt)]\npub struct Cw310Opts {\n #[structopt(\n long,\n help = \"Comma-separated list of CW310 UARTs for non-udev environments. List the console uart first.\"\n )]\n pub cw310_uarts: Option<String>,\n}\n\npub fn create(args: &BackendOpts) -> Result<Box<dyn Transport>> {\n let uarts = args\n .cw310_opts\n .cw310_uarts\n .as_ref()\n .map(|v| v.split(',').collect::<Vec<&str>>())\n .unwrap_or(Vec::new());\n Ok(Box::new(CW310::new(\n args.usb_vid,\n args.usb_pid,\n args.usb_serial.as_deref(),\n &uarts,\n )?))\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add FIXME to file reading test\n" }, { "from": "human", "value": "// ignore-windows: File handling is not implemented yet\n// compile-flags: -Zmiri-disable-isolation\n\nuse std::fs::File;\nuse std::io::Read;\n\nfn main() {\n let mut file = File::open(\"./tests/hello.txt\").unwrap();\n let mut contents = String::new();\n file.read_to_string(&mut contents).unwrap();\n assert_eq!(\"Hello, World!\\n\", contents);\n}\n" }, { "from": "gpt", "value": "// ignore-windows: File handling is not implemented yet\n// compile-flags: -Zmiri-disable-isolation\n\nuse std::fs::File;\nuse std::io::Read;\n\nfn main() {\n // FIXME: create the file and delete it when `rm` is implemented.\n let mut file = File::open(\"./tests/hello.txt\").unwrap();\n let mut contents = String::new();\n file.read_to_string(&mut contents).unwrap();\n assert_eq!(\"Hello, World!\\n\", contents);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "test: Fix name of bitv type\n" }, { "from": "human", "value": "// error-pattern: mismatched types\nuse std;\nimport std::map::hashmap;\nimport std::bitv;\n\ntype fn_info = {vars: hashmap<uint, var_info>};\ntype var_info = {a: uint, b: uint};\n\nfn bitv_to_str(enclosing: fn_info, v: bitv::t) -> str {\n let s = \"\";\n\n // error is that the value type in the hash map is var_info, not a box\n enclosing.vars.values {|val|\n if bitv::get(v, val) { s += \"foo\"; }\n }\n ret s;\n}\n\nfn main() { #debug(\"OK\"); }\n" }, { "from": "gpt", "value": "// error-pattern: mismatched types\nuse std;\nimport std::map::hashmap;\nimport std::bitv;\n\ntype fn_info = {vars: hashmap<uint, var_info>};\ntype var_info = {a: uint, b: uint};\n\nfn bitv_to_str(enclosing: fn_info, v: bitv::bitv) -> str {\n let s = \"\";\n\n // error is that the value type in the hash map is var_info, not a box\n enclosing.vars.values {|val|\n if bitv::get(v, val) { s += \"foo\"; }\n }\n ret s;\n}\n\nfn main() { #debug(\"OK\"); }\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix the UUID Parcel implementation\n" }, { "from": "human", "value": "use {Parcel, Error, Settings};\nuse std::io::prelude::*;\n\nuse uuid::Uuid;\n\nimpl Parcel for Uuid\n{\n fn read(read: &mut Read,\n settings: &Settings,\n _: &mut hint::Hints)\n -> Result<Self, Error> {\n let bytes: Result<Vec<u8>, _> = read.bytes().take(16).collect();\n let bytes = bytes?;\n\n Ok(Uuid::from_bytes(&bytes)?)\n }\n\n fn write(&self, write: &mut Write) -> Result<(), Error> {\n write.write(self.as_bytes())?;\n Ok(())\n }\n}\n\n" }, { "from": "gpt", "value": "use {Parcel, Error, Settings};\nuse hint;\nuse std::io::prelude::*;\n\nuse uuid::Uuid;\n\nimpl Parcel for Uuid\n{\n const TYPE_NAME: &'static str = \"Uuid\";\n\n fn read(read: &mut Read,\n _: &Settings,\n _: &mut hint::Hints)\n -> Result<Self, Error> {\n let bytes: Result<Vec<u8>, _> = read.bytes().take(16).collect();\n let bytes = bytes?;\n\n Ok(Uuid::from_bytes(&bytes)?)\n }\n\n fn write(&self, write: &mut Write,\n _: &Settings) -> Result<(), Error> {\n write.write(self.as_bytes())?;\n Ok(())\n }\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a `stop` function to `Application`.\n" }, { "from": "human", "value": "use glutin::Window;\n\nuse event::{Event, PollEvents, Reactor};\nuse render::{Context, GlutinContext, MetaContext};\n\npub struct Harness<A, C>\n where A: Application<C>,\n C: MetaContext\n{\n application: A,\n context: Context<C>,\n}\n\nimpl<A> Harness<A, GlutinContext>\n where A: Application<GlutinContext>\n{\n pub fn from_glutin_window(application: A, window: Window) -> Self {\n Harness {\n application: application,\n context: Context::from_glutin_window(window),\n }\n }\n}\n\nimpl<A, C> Harness<A, C>\n where A: Application<C>,\n C: MetaContext\n{\n pub fn start(&mut self) {\n 'main: loop {\n for event in self.context.window.poll_events() {\n match event {\n Event::Closed => {\n break 'main;\n }\n Event::Resized(..) => {\n self.context.update_frame_buffer_view();\n }\n _ => {}\n }\n self.application.react(&event);\n }\n self.context.clear();\n // TODO: Do not lend the entire `Context`. Maybe `Context` can emit\n // a more limited type that can be used for rendering.\n self.application.render(&mut self.context);\n self.context.flush().unwrap();\n }\n }\n}\n\npub trait Application<C>: Reactor\n where C: MetaContext\n{\n fn render(&mut self, context: &mut Context<C>);\n}\n" }, { "from": "gpt", "value": "use glutin::Window;\n\nuse event::{Event, PollEvents, Reactor};\nuse render::{Context, GlutinContext, MetaContext};\n\npub struct Harness<A, C>\n where A: Application<C>,\n C: MetaContext\n{\n application: A,\n context: Context<C>,\n}\n\nimpl<A> Harness<A, GlutinContext>\n where A: Application<GlutinContext>\n{\n pub fn from_glutin_window(application: A, window: Window) -> Self {\n Harness {\n application: application,\n context: Context::from_glutin_window(window),\n }\n }\n}\n\nimpl<A, C> Harness<A, C>\n where A: Application<C>,\n C: MetaContext\n{\n pub fn start(&mut self) {\n 'main: loop {\n for event in self.context.window.poll_events() {\n match event {\n Event::Closed => {\n break 'main;\n }\n Event::Resized(..) => {\n self.context.update_frame_buffer_view();\n }\n _ => {}\n }\n self.application.react(&event);\n }\n self.context.clear();\n self.application.render(&mut self.context);\n self.context.flush().unwrap();\n }\n self.application.stop();\n }\n}\n\npub trait Application<C>: Reactor\n where C: MetaContext\n{\n // TODO: Do not accept the entire `Context`. Maybe `Context` can emit a\n // more limited type that can be used for rendering.\n fn render(&mut self, context: &mut Context<C>);\n fn stop(&mut self) {}\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add basic packet read, including unsafe conversion\n" }, { "from": "human", "value": "//! Contains code to handle an IPC channel which is issuing commands.\n\nuse std::io::prelude::*;\n\nuse rustc_serialize::Decodable;\nuse rustc_serialize::json::{Json, ToJson, Decoder, EncoderError};\n\nuse unix_socket::UnixStream;\n\n/// Reasons a client message might be erroneous\n#[derive(Debug, Clone)]\nenum ResponseError {\n /// Connection was closed\n ConnectionClosed,\n /// Json was invalid\n InvalidJson(EncoderError)\n}\n\n/// Receives a packet from the given stream.\nfn receive_packet(stream: &mut UnixStream) -> Result<Json, ResponseError> {\n Err(ResponseError::ConnectionClosed)\n}\n\npub fn handle_client(mut stream: UnixStream) {\n println!(\"Starting connection.\");\n\n // Listen for starting connection\n}\n\nfn command(mut stream: UnixStream) {\n \n}\n\nfn event(mut stream: UnixStream) {\n \n}\n" }, { "from": "gpt", "value": "//! Contains code to handle an IPC channel which is issuing commands.\n\nuse std::io::Error as IOError;\nuse std::io::prelude::*;\n\nuse rustc_serialize::Decodable;\nuse rustc_serialize::json::{Json, ToJson, Decoder, ParserError, EncoderError};\n\nuse unix_socket::UnixStream;\n\n/// Reasons a client message might be erroneous\n#[derive(Debug)]\nenum ResponseError {\n /// Connection was closed\n ConnectionClosed,\n /// Some bytes dun goofed\n InvalidString,\n /// There were IO issues\n IO(IOError),\n /// Json was invalid\n InvalidJson(ParserError)\n}\n\n/// Receives a packet from the given stream.\nfn receive_packet(stream: &mut Read) -> Result<Json, ResponseError> {\n let mut buffer = [0u8; 4];\n try!(stream.read_exact(&mut buffer).map_err(ResponseError::IO));\n // This is what the byteorder crate does (needs testing)\n let len = u32::from_be(unsafe { buffer.as_ptr() as *const u32 } as u32);\n trace!(\"Listening for packet of length {}\", len);\n return Json::from_reader(&mut stream.take(len as u64))\n .map_err(ResponseError::InvalidJson);\n}\n\npub fn handle_client(mut stream: UnixStream) {\n println!(\"Starting connection.\");\n\n // Listen for starting connection\n}\n\nfn command(mut stream: UnixStream) {\n \n}\n\nfn event(mut stream: UnixStream) {\n \n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Allow append_path to be unused\n" }, { "from": "human", "value": "use std::ffi::OsString;\nuse std::env;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\npub fn append_path(name: &str, value: Vec<PathBuf>, cmd: &mut Command) {\n let old_value = env::var_os(name);\n let mut parts: Vec<PathBuf>;\n if let Some(ref v) = old_value {\n parts = env::split_paths(v).collect();\n parts.extend(value);\n } else {\n parts = value;\n }\n if let Ok(new_value) = env::join_paths(parts) {\n cmd.env(name, new_value);\n }\n}\n\npub fn prepend_path(name: &str, value: &Path, cmd: &mut Command) {\n let old_value = env::var_os(name);\n let mut parts = vec![value.to_owned()];\n if let Some(ref v) = old_value {\n parts.extend(env::split_paths(v));\n }\n let new_value = env::join_paths(parts).unwrap_or_else(|_| OsString::from(value));\n\n cmd.env(name, new_value);\n}\n\npub fn inc(name: &str, cmd: &mut Command) {\n let old_value = env::var(name)\n .ok()\n .and_then(|v| v.parse().ok())\n .unwrap_or(0);\n\n cmd.env(name, (old_value + 1).to_string());\n}\n" }, { "from": "gpt", "value": "use std::ffi::OsString;\nuse std::env;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\n#[allow(unused)]\npub fn append_path(name: &str, value: Vec<PathBuf>, cmd: &mut Command) {\n let old_value = env::var_os(name);\n let mut parts: Vec<PathBuf>;\n if let Some(ref v) = old_value {\n parts = env::split_paths(v).collect();\n parts.extend(value);\n } else {\n parts = value;\n }\n if let Ok(new_value) = env::join_paths(parts) {\n cmd.env(name, new_value);\n }\n}\n\npub fn prepend_path(name: &str, value: &Path, cmd: &mut Command) {\n let old_value = env::var_os(name);\n let mut parts = vec![value.to_owned()];\n if let Some(ref v) = old_value {\n parts.extend(env::split_paths(v));\n }\n let new_value = env::join_paths(parts).unwrap_or_else(|_| OsString::from(value));\n\n cmd.env(name, new_value);\n}\n\npub fn inc(name: &str, cmd: &mut Command) {\n let old_value = env::var(name)\n .ok()\n .and_then(|v| v.parse().ok())\n .unwrap_or(0);\n\n cmd.env(name, (old_value + 1).to_string());\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use clap's required_unless to enforce input file path\n" }, { "from": "human", "value": "mod gen;\nmod syntax;\n\nuse gen::include;\nuse std::io::{self, Write};\nuse std::path::PathBuf;\nuse std::process;\nuse structopt::StructOpt;\n\n#[derive(StructOpt, Debug)]\n#[structopt(name = \"cxxbridge\", author)]\nstruct Opt {\n /// Input Rust source file containing #[cxx::bridge]\n #[structopt(parse(from_os_str))]\n input: Option<PathBuf>,\n\n /// Emit header with declarations only\n #[structopt(long)]\n header: bool,\n}\n\nfn main() {\n let opt = Opt::from_args();\n\n if let Some(input) = opt.input {\n let gen = if opt.header {\n gen::do_generate_header\n } else {\n gen::do_generate_bridge\n };\n let bridge = gen(&input);\n let _ = io::stdout().lock().write_all(bridge.as_ref());\n } else if opt.header {\n let header = include::HEADER;\n let _ = io::stdout().lock().write_all(header.as_ref());\n } else {\n let _ = Opt::clap().after_help(\"\").print_help();\n process::exit(1);\n }\n}\n" }, { "from": "gpt", "value": "mod gen;\nmod syntax;\n\nuse gen::include;\nuse std::io::{self, Write};\nuse std::path::PathBuf;\nuse structopt::StructOpt;\n\n#[derive(StructOpt, Debug)]\n#[structopt(name = \"cxxbridge\", author)]\nstruct Opt {\n /// Input Rust source file containing #[cxx::bridge]\n #[structopt(parse(from_os_str), required_unless = \"header\")]\n input: Option<PathBuf>,\n\n /// Emit header with declarations only\n #[structopt(long)]\n header: bool,\n}\n\nfn write(content: impl AsRef<[u8]>) {\n let _ = io::stdout().lock().write_all(content.as_ref());\n}\n\nfn main() {\n let opt = Opt::from_args();\n\n match (opt.input, opt.header) {\n (Some(input), true) => write(gen::do_generate_header(&input)),\n (Some(input), false) => write(gen::do_generate_bridge(&input)),\n (None, true) => write(include::HEADER),\n (None, false) => unreachable!(), // enforced by required_unless\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add optional search path for static linking\n" }, { "from": "human", "value": "fn main() {\n if cfg!(r#static) {\n println!(\"cargo:rustc-link-lib=static=odbc\");\n }\n\n if cfg!(target_os = \"macos\") {\n // if we're on Mac OS X we'll kindly add DYLD_LIBRARY_PATH to rustc's\n // linker search path\n if let Some(dyld_paths) = option_env!(\"DYLD_LIBRARY_PATH\") {\n print_paths(dyld_paths);\n }\n // if we're on Mac OS X we'll kindly add DYLD_FALLBACK_LIBRARY_PATH to rustc's\n // linker search path\n if let Some(dyld_fallback_paths) = option_env!(\"DYLD_FALLBACK_LIBRARY_PATH\") {\n print_paths(dyld_fallback_paths);\n }\n }\n}\n\nfn print_paths(paths: &str) {\n for path in paths.split(':').filter(|x| !x.is_empty()) {\n println!(\"cargo:rustc-link-search=native={}\", path)\n }\n}\n" }, { "from": "gpt", "value": "fn main() {\n if cfg!(r#static) {\n let static_path = std::env::var(\"ODBC_SYS_STATIC_PATH\").unwrap_or(\"/usr/lib\".to_string());\n println!(\"cargo:rerun-if-env-changed=ODBC_SYS_STATIC_PATH\");\n println!(\"cargo:rustc-link-search=native={}\", static_path);\n println!(\"cargo:rustc-link-lib=static=odbc\");\n }\n\n if cfg!(target_os = \"macos\") {\n // if we're on Mac OS X we'll kindly add DYLD_LIBRARY_PATH to rustc's\n // linker search path\n if let Some(dyld_paths) = option_env!(\"DYLD_LIBRARY_PATH\") {\n print_paths(dyld_paths);\n }\n // if we're on Mac OS X we'll kindly add DYLD_FALLBACK_LIBRARY_PATH to rustc's\n // linker search path\n if let Some(dyld_fallback_paths) = option_env!(\"DYLD_FALLBACK_LIBRARY_PATH\") {\n print_paths(dyld_fallback_paths);\n }\n }\n}\n\nfn print_paths(paths: &str) {\n for path in paths.split(':').filter(|x| !x.is_empty()) {\n println!(\"cargo:rustc-link-search=native={}\", path)\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Improve previous compile fail test\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#![deny(warnings)]\nuse std::thread; //~ ERROR: unused import\nfn main() {}\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#![deny(warnings)] //~ NOTE: lint level defined here\nuse std::thread; //~ ERROR: unused import\nfn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add short documentation of the root module for `client`\n" }, { "from": "human", "value": "extern crate base;\n#[macro_use]\nextern crate glium;\n#[macro_use]\nextern crate log;\n\npub mod render;\npub mod event_manager;\nmod config;\nmod game;\n\npub use config::Config;\n\n\npub fn start_game(config: Config, world_provider: &base::world::Provider) -> Result<(), ()> {\n game::run(&config, world_provider)\n}\n" }, { "from": "gpt", "value": "//! This crate contains functionality for the client only. This is mainly\n//! graphics and input handling.\n//!\n\nextern crate base;\n#[macro_use]\nextern crate glium;\n#[macro_use]\nextern crate log;\n\npub mod render;\npub mod event_manager;\nmod config;\nmod game;\n\npub use config::Config;\n\n\npub fn start_game(config: Config, world_provider: &base::world::Provider) -> Result<(), ()> {\n game::run(&config, world_provider)\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix regression in line ending test\n" }, { "from": "human", "value": "// run-pass\n// ignore-tidy-cr\n\n// this file has some special \\r\\n endings (use xxd to see them)\n\nfn main() {assert_eq!(b\"\", b\"\\\n \");\nassert_eq!(b\"\\n\", b\"\n\");\n}\n" }, { "from": "gpt", "value": "// run-pass\n// ignore-tidy-cr\n\n// this file has some special \\r\\n endings (use xxd to see them)\n\nfn main() {assert_eq!(b\"\", b\"\\\r\n \");\nassert_eq!(b\"\\n\", b\"\r\n\");\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove 'u' from number literals" }, { "from": "human", "value": "extern crate rust_guessing_game;\n\nuse std::old_io as io;\nuse std::rand;\nuse std::cmp::Ordering;\n\nuse rust_guessing_game::my_funcs;\n\n#[cfg(not(test))]\nfn main() {\n println!(\"Guess the magic number!\");\n let magic_number = ( rand::random::<usize>() % 100u ) + 1u;\n loop {\n let input = io::stdin().read_line().ok().expect(\"That was bad input\");\n let input_optoin_usize: Option<usize> = input.parse();\n let input_usize = match input_optoin_usize {\n Some(num) => num,\n None => {\n println!(\"Please input a number\");\n continue;\n }\n };\n match my_funcs::compare(input_usize, magic_number) {\n Ordering::Less => println!(\"Guess higher.\"),\n Ordering::Greater => println!(\"Guess lower.\"),\n Ordering::Equal => { \n println!(\"You win!\"); \n return\n },\n }\n }\n}\n" }, { "from": "gpt", "value": "extern crate rust_guessing_game;\n\nuse std::old_io as io;\nuse std::rand;\nuse std::cmp::Ordering;\n\nuse rust_guessing_game::my_funcs;\n\n#[cfg(not(test))]\nfn main() {\n println!(\"Guess the magic number!\");\n let magic_number = ( rand::random::<usize>() % 100 ) + 1;\n loop {\n let input = io::stdin().read_line().ok().expect(\"That was bad input\");\n let input_optoin_usize: Option<usize> = input.parse();\n let input_usize = match input_optoin_usize {\n Some(num) => num,\n None => {\n println!(\"Please input a number\");\n continue;\n }\n };\n match my_funcs::compare(input_usize, magic_number) {\n Ordering::Less => println!(\"Guess higher.\"),\n Ordering::Greater => println!(\"Guess lower.\"),\n Ordering::Equal => { \n println!(\"You win!\"); \n return\n },\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Sort import by specificity, then alphabetize.\n\nSigned-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>\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\nuse std::fmt::Debug;\nuse std::path::Path;\nuse std::collections::BTreeMap;\nuse types::StratisResult;\n\n\npub trait Pool: Debug {\n fn add_blockdev(&mut self, path: &str) -> StratisResult<()>;\n fn add_cachedev(&mut self, path: &str) -> StratisResult<()>;\n fn destroy(&mut self) -> StratisResult<()>;\n fn get_name(&mut self) -> String;\n fn copy(&self) -> Box<Pool>;\n}\n\npub trait Engine: Debug {\n fn create_pool(&mut self,\n name: &str,\n blockdev_paths: &[&Path],\n raid_level: u16)\n -> StratisResult<()>;\n\n fn destroy_pool(&mut self, name: &str) -> StratisResult<()>;\n fn list_pools(&self) -> StratisResult<BTreeMap<String, Box<Pool>>>;\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\n\nuse std::collections::BTreeMap;\nuse std::fmt::Debug;\nuse std::path::Path;\n\nuse types::StratisResult;\n\n\npub trait Pool: Debug {\n fn add_blockdev(&mut self, path: &str) -> StratisResult<()>;\n fn add_cachedev(&mut self, path: &str) -> StratisResult<()>;\n fn destroy(&mut self) -> StratisResult<()>;\n fn get_name(&mut self) -> String;\n fn copy(&self) -> Box<Pool>;\n}\n\npub trait Engine: Debug {\n fn create_pool(&mut self,\n name: &str,\n blockdev_paths: &[&Path],\n raid_level: u16)\n -> StratisResult<()>;\n\n fn destroy_pool(&mut self, name: &str) -> StratisResult<()>;\n fn list_pools(&self) -> StratisResult<BTreeMap<String, Box<Pool>>>;\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add function to convert roman numerals into decimal numbers.\n" }, { "from": "human", "value": "/*\n** A simple program that allows basic arithmetic operations using roman numerals and conversions to decimal numbers.\n*/\n\nfn main() {\n println!(\"Bismillah\");\n}" }, { "from": "gpt", "value": "/*\n** A simple program that allows basic arithmetic operations using roman numerals and conversions to decimal numbers.\n*/\n\nfn main() {\n\n\tlet roman_number = \"CLIII\";\n\tlet decimal_number = to_decimal(&roman_number);\n\n\tprintln!(\"The roman number {} is equal to {} in decimal numbers\", roman_number, decimal_number);\n\n\tlet roman_number = \"XXXIV\";\n\tlet decimal_number = to_decimal(&roman_number);\n\n\tprintln!(\"The roman number {} is equal to {} in decimal numbers\", roman_number, decimal_number);\n}\n\nfn to_decimal(roman_number: &str) -> i32 {\n\n\tlet mut num = 0;\n\n\tfor c in roman_number.chars() {\n\t\tnum += roman_char_to_decimal(c);\n\t}\n\n\tnum\n}\n\nfn roman_char_to_decimal(roman_char: char) -> i32 {\n\n\tmatch roman_char {\n\t 'I' => 1,\n\t 'V' => 5,\n\t 'X' => 10,\n\t 'L' => 50,\n\t 'C' => 100,\n\t 'D' => 500,\n\t 'M' => 1000,\n\t _ => 0,\n\t}\n}" } ]
rust
chosen
[ { "from": "system", "value": "Add file allow annotations for warnings\n" }, { "from": "human", "value": "use syntax::ast;\nuse syntax::ast::{MetaItem, Expr};\nuse syntax::codemap::Span;\nuse syntax::ext::base::{Annotatable, ExtCtxt};\nuse syntax::ext::build::AstBuilder;\nuse syntax::ext::deriving::generic::{Struct, Substructure, TraitDef, ty};\nuse syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef};\n\npub fn expand_action_annotation(context: &mut ExtCtxt,\n span: Span,\n meta_item: &MetaItem,\n item: &Annotatable,\n push: &mut FnMut(Annotatable)) {\n\n}" }, { "from": "gpt", "value": "#![allow(dead_code, unused_imports, unused_variables)]\n\nuse syntax::ast;\nuse syntax::ast::{MetaItem, Expr};\nuse syntax::codemap::Span;\nuse syntax::ext::base::{Annotatable, ExtCtxt};\nuse syntax::ext::build::AstBuilder;\nuse syntax::ext::deriving::generic::{Struct, Substructure, TraitDef, ty};\nuse syntax::ext::deriving::generic::{combine_substructure, EnumMatching, FieldInfo, MethodDef};\n\npub fn expand_action_annotation(context: &mut ExtCtxt,\n span: Span,\n meta_item: &MetaItem,\n item: &Annotatable,\n push: &mut FnMut(Annotatable)) {\n\n}" } ]
rust
chosen
[ { "from": "system", "value": "Remove unneeded features (and unneeded attribute)\n" }, { "from": "human", "value": "#![cfg_attr(feature=\"clippy\", feature(plugin))]\n#![cfg_attr(feature=\"clippy\", plugin(clippy))]\n#![feature(conservative_impl_trait)]\n#![feature(collections_bound)]\n#![feature(btree_range)]\n#![feature(step_by)]\n\n#![allow(dead_code)]\nextern crate chrono;\nextern crate nom;\n\nmod time_unit;\nmod schedule;\n\npub use schedule::Schedule;\n" }, { "from": "gpt", "value": "#![cfg_attr(feature=\"clippy\", feature(plugin))]\n#![cfg_attr(feature=\"clippy\", plugin(clippy))]\n#![feature(conservative_impl_trait)]\n#![feature(step_by)]\n\nextern crate chrono;\nextern crate nom;\n\nmod time_unit;\nmod schedule;\n\npub use schedule::Schedule;\n" } ]
rust
chosen
[ { "from": "system", "value": "Test is the file actually is created\n" }, { "from": "human", "value": "#[macro_use]\nextern crate serde_elm;\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 assert!(true);\n}\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate serde_elm;\n\nuse std::env;\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 let mut path = env::current_dir().unwrap();\n path.push(\"generated\");\n path.push(\"Simple.elm\");\n\n assert!(path.exists());\n assert!(path.is_file());\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Improve documentation for new Validation trait\n" }, { "from": "human", "value": "/// Validation provider\npub trait Validator {\n fn is_valid(&self, line: &str) -> bool;\n}\n\nimpl Validator for () {\n fn is_valid(&self, _line: &str) -> bool {\n true\n }\n}\n" }, { "from": "gpt", "value": "//! Input buffer validation API (Multi-line editing)\n\n/// This trait provides an extension interface for determining whether\n/// the current input buffer is valid. Rustyline uses the method\n/// provided by this trait to decide whether hitting the enter key\n/// will end the current editing session and return the current line\n/// buffer to the caller of `Editor::readline` or variants.\npub trait Validator {\n /// Takes the currently edited `line` and returns a bool\n /// indicating whether it is valid or not. The most common\n /// validity check to implement is probably whether the input is\n /// complete or not, for instance ensuring that all delimiters are\n /// fully balanced.\n ///\n /// If you implement more complex validation checks it's probably\n /// a good idea to also implement a `Hinter` to provide feedback\n /// about what is invalid.\n #[allow(unused_variables)]\n fn is_valid(&self, line: &str) -> bool {\n true\n }\n}\n\nimpl Validator for () {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make sure the submodule is brought in\n" }, { "from": "human", "value": "use std::io::Command;\nuse std::os;\n\nfn main() {\n let curr_dir = os::getenv(\"CARGO_MANIFEST_DIR\").unwrap();\n let nvim_dir = Path::new(curr_dir).join(\"neovim\");\n Command::new(\"make\").arg(\"libnvim\").cwd(&nvim_dir).status().unwrap();\n\n let nvim_lib_dir = nvim_dir.join_many(&[\"build\", \"src\", \"nvim\"]);\n let deps_lib_dir = nvim_dir.join_many(&[\".deps\", \"usr\", \"lib\"]);\n println!(\"cargo:rustc-flags=-L {} -L {} -l nvim:static -l nvim -l uv -l msgpack -l curses\",\n nvim_lib_dir.as_str().unwrap(),\n deps_lib_dir.as_str().unwrap());\n}\n" }, { "from": "gpt", "value": "use std::io::Command;\nuse std::os;\n\nfn main() {\n let curr_dir = Path::new(os::getenv(\"CARGO_MANIFEST_DIR\").unwrap());\n Command::new(\"git\").arg(\"submodule\").arg(\"update\").arg(\"--init\").cwd(&curr_dir).status().unwrap();\n\n let nvim_dir = Path::new(curr_dir).join(\"neovim\");\n Command::new(\"make\").arg(\"libnvim\").cwd(&nvim_dir).status().unwrap();\n\n let nvim_lib_dir = nvim_dir.join_many(&[\"build\", \"src\", \"nvim\"]);\n let deps_lib_dir = nvim_dir.join_many(&[\".deps\", \"usr\", \"lib\"]);\n println!(\"cargo:rustc-flags=-L {} -L {} -l nvim:static -l nvim -l uv -l msgpack -l curses\",\n nvim_lib_dir.as_str().unwrap(),\n deps_lib_dir.as_str().unwrap());\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use Inline assembly for msvc target from non-windows host\n\nWhen cross-compiling for msvc from a non-windows host, inline assembly is typically supported (for example via clang or clang-cl). Given that clang also doesn't support masm or have ml.exe compatibility, it's best to use the C implementations of `util_helpers` and `aesni_helpers`." }, { "from": "human", "value": "// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nextern crate gcc;\n\nuse std::env;\n\nfn main() {\n let target = env::var(\"TARGET\").unwrap();\n if target.contains(\"msvc\") {\n let mut config = gcc::Config::new();\n config.file(\"src/util_helpers.asm\");\n config.file(\"src/aesni_helpers.asm\");\n if target.contains(\"x86_64\") {\n config.define(\"X64\", None);\n }\n config.compile(\"lib_rust_crypto_helpers.a\");\n } else {\n gcc::compile_library(\n \"lib_rust_crypto_helpers.a\",\n &[\"src/util_helpers.c\", \"src/aesni_helpers.c\"]);\n }\n}\n\n" }, { "from": "gpt", "value": "// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nextern crate gcc;\n\nuse std::env;\n\nfn main() {\n let target = env::var(\"TARGET\").unwrap();\n let host = env::var(\"HOST\").unwrap();\n if target.contains(\"msvc\") && host.contains(\"windows\") {\n let mut config = gcc::Config::new();\n config.file(\"src/util_helpers.asm\");\n config.file(\"src/aesni_helpers.asm\");\n if target.contains(\"x86_64\") {\n config.define(\"X64\", None);\n }\n config.compile(\"lib_rust_crypto_helpers.a\");\n } else {\n gcc::compile_library(\n \"lib_rust_crypto_helpers.a\",\n &[\"src/util_helpers.c\", \"src/aesni_helpers.c\"]);\n }\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unnecessary referencing in the hash comparison\n" }, { "from": "human", "value": "use data_encoding::{BASE64URL, DecodeError};\n\npub fn check_access_token<T: AsRef<str>>(token: T, salt: T, hash: T) -> bool {\n let hashed_token = salt_and_hash(salt, token);\n let should_be = BASE64URL.decode(hash.as_ref().as_bytes());\n\n match (hashed_token, should_be) {\n (Ok(ref a), Ok(ref b)) if &a[..] == &b[..] => true,\n _ => false,\n }\n}\n\nfn salt_and_hash<T: AsRef<str>>(salt: T, token: T) -> Result<Vec<u8>, DecodeError> {\n use blake2::{Blake2s, Digest};\n\n let salt_bytes = BASE64URL.decode(salt.as_ref().as_bytes())?;\n let token_bytes = BASE64URL.decode(token.as_ref().as_bytes())?;\n\n let mut hasher = Blake2s::default();\n hasher.input(&salt_bytes[..]);\n hasher.input(&token_bytes[..]);\n\n Ok(hasher.result().into_iter().collect())\n}\n" }, { "from": "gpt", "value": "use data_encoding::{BASE64URL, DecodeError};\n\npub fn check_access_token<T: AsRef<str>>(token: T, salt: T, hash: T) -> bool {\n let hashed_token = salt_and_hash(salt, token);\n let should_be = BASE64URL.decode(hash.as_ref().as_bytes());\n\n match (hashed_token, should_be) {\n (Ok(ref a), Ok(ref b)) if a[..] == b[..] => true,\n _ => false,\n }\n}\n\nfn salt_and_hash<T: AsRef<str>>(salt: T, token: T) -> Result<Vec<u8>, DecodeError> {\n use blake2::{Blake2s, Digest};\n\n let salt_bytes = BASE64URL.decode(salt.as_ref().as_bytes())?;\n let token_bytes = BASE64URL.decode(token.as_ref().as_bytes())?;\n\n let mut hasher = Blake2s::default();\n hasher.input(&salt_bytes[..]);\n hasher.input(&token_bytes[..]);\n\n Ok(hasher.result().into_iter().collect())\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add `IndexDatum` impls for `u8`/`u16`\n" }, { "from": "human", "value": "pub use std::mem;\npub use std::slice;\n\npub enum IndexDatumType {\n UnsignedByte,\n UnsignedShort\n}\n\npub trait IndexData {\n fn index_datum_type() -> IndexDatumType;\n fn index_bytes(&self) -> &[u8];\n fn index_elements(&self) -> usize;\n}\n\npub trait IndexDatum {\n fn index_datum_type() -> IndexDatumType;\n}\n" }, { "from": "gpt", "value": "pub use std::mem;\npub use std::slice;\n\npub enum IndexDatumType {\n UnsignedByte,\n UnsignedShort\n}\n\npub trait IndexData {\n fn index_datum_type() -> IndexDatumType;\n fn index_bytes(&self) -> &[u8];\n fn index_elements(&self) -> usize;\n}\n\npub trait IndexDatum {\n fn index_datum_type() -> IndexDatumType;\n}\n\nimpl IndexDatum for u8 {\n fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedByte }\n}\n\nimpl IndexDatum for u16 {\n fn index_datum_type() -> IndexDatumType { IndexDatumType::UnsignedShort }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Print message instead of disabling challenge\n" }, { "from": "human", "value": "use super::hmac_client;\nuse super::hmac_server;\n\nuse rand;\nuse rand::Rng;\n\nuse errors::*;\n\npub fn run() -> Result<(), Error> {\n let skip_exercise = true;\n\n if skip_exercise {\n return Err(ChallengeError::Skipped(\"Runs very long.\").into());\n }\n\n let mut rng = rand::thread_rng();\n let key: Vec<u8> = rng.gen_iter().take(20).collect();\n\n let mut server = hmac_server::start(key)?;\n let result = hmac_client::run();\n server.close().context(\"failed to close connection\")?;\n\n result\n}\n" }, { "from": "gpt", "value": "use super::hmac_client;\nuse super::hmac_server;\n\nuse rand;\nuse rand::Rng;\n\nuse errors::*;\n\npub fn run() -> Result<(), Error> {\n println!(\"Challenge 32: takes about three minutes, pleases wait ...\");\n let mut rng = rand::thread_rng();\n let key: Vec<u8> = rng.gen_iter().take(20).collect();\n\n let mut server = hmac_server::start(key)?;\n let result = hmac_client::run();\n server.close().context(\"failed to close connection\")?;\n\n result\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Fix nightly check in serde-syntex-example\n" }, { "from": "human", "value": "#![cfg_attr(nightly, feature(custom_derive, plugin))]\n#![cfg_attr(nightly, plugin(serde_macros))]\n\nextern crate serde;\nextern crate serde_json;\n\n#[cfg(feature = \"serde_macros\")]\ninclude!(\"main.rs.in\");\n\n#[cfg(not(feature = \"serde_macros\"))]\ninclude!(concat!(env!(\"OUT_DIR\"), \"/main.rs\"));\n" }, { "from": "gpt", "value": "#![cfg_attr(feature = \"serde_macros\", feature(custom_derive, plugin))]\n#![cfg_attr(feature = \"serde_macros\", plugin(serde_macros))]\n\nextern crate serde;\nextern crate serde_json;\n\n#[cfg(feature = \"serde_macros\")]\ninclude!(\"main.rs.in\");\n\n#[cfg(not(feature = \"serde_macros\"))]\ninclude!(concat!(env!(\"OUT_DIR\"), \"/main.rs\"));\n" } ]
rust
chosen
[ { "from": "system", "value": "Handle divide by zero errors\n" }, { "from": "human", "value": "use parser::Expr;\nuse parser::Expr::*;\n\n// The main entry point for the calculator itself.\n// It receives an expression tree, and recursively reduces it to a single signed 64-bit integer\npub fn evaluate(expr: &Expr) -> i64 {\n match expr {\n &Int(ref i) => *i,\n &Plus(box ref l, box ref r) => evaluate(&l) + evaluate(&r),\n &Minus(box ref l, box ref r) => evaluate(&l) - evaluate(&r),\n &Mul(box ref l, box ref r) => evaluate(&l) * evaluate(&r),\n &Div(box ref l, box ref r) => evaluate(&l) / evaluate(&r),\n &Pow(box ref l, box ref r) => evaluate(&l).pow(evaluate(&r) as u32)\n }\n}\n" }, { "from": "gpt", "value": "use parser::Expr;\nuse parser::Expr::*;\n\n// The main entry point for the calculator itself.\n// It receives an expression tree, and recursively reduces it to a single signed 64-bit integer\npub fn evaluate(expr: &Expr) -> i64 {\n match expr {\n &Int(ref i) => *i,\n &Plus(box ref l, box ref r) => evaluate(&l) + evaluate(&r),\n &Minus(box ref l, box ref r) => evaluate(&l) - evaluate(&r),\n &Mul(box ref l, box ref r) => evaluate(&l) * evaluate(&r),\n &Pow(box ref l, box ref r) => evaluate(&l).pow(evaluate(&r) as u32),\n &Div(box ref l, box ref r) => {\n let numerator = evaluate(&l);\n let divisor = evaluate(&r);\n match divisor {\n n if n == 0 => 0i64,\n _ => numerator / divisor\n }\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Rename List to Repository to avoid ambiguity\n" }, { "from": "human", "value": "enum PackageType {\n Bin, // Binary\n Lib, // Library\n Src, // Source\n}\n\nstruct Version {\n major: u32,\n minor: u32,\n patch: u32,\n additional: Option<String>,\n}\n\nstruct Package {\n name: String,\n hash: u32,\n version: Version,\n package_type: PackageType,\n dependencies: Vec<Package>, \n}\n\nstruct List {\n url: String,\n packages: Vec<Package>,\n}" }, { "from": "gpt", "value": "enum PackageType {\n Bin, // Binary\n Lib, // Library\n Src, // Source\n}\n\nstruct Version {\n major: u32,\n minor: u32,\n patch: u32,\n additional: Option<String>,\n}\n\nstruct Package {\n name: String,\n hash: u32,\n version: Version,\n package_type: PackageType,\n dependencies: Vec<Package>, \n}\n\nstruct Repository {\n url: String,\n packages: Vec<Package>,\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add fixme for parsing error\n" }, { "from": "human", "value": "use std::fmt;\nuse std::error::Error;\n\n#[derive(Debug)]\npub struct ParsingError {\n desc: String,\n}\n\nimpl fmt::Display for ParsingError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n self.description().fmt(f)\n }\n}\n\nimpl Error for ParsingError {\n fn description(&self) -> &str {\n self.desc.as_slice()\n }\n\n fn cause(&self) -> Option<&Error> {\n None\n }\n}\n\nimpl ParsingError {\n pub fn new(desc: String) -> Self {\n ParsingError {\n desc: desc\n }\n }\n}\n\npub type ParsingResult<T> = Result<T, ParsingError>;\n" }, { "from": "gpt", "value": "use std::fmt;\nuse std::error::Error;\n\n#[derive(Debug)]\npub struct ParsingError {\n desc: String, // FIXME: Too basic\n}\n\nimpl fmt::Display for ParsingError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n self.description().fmt(f)\n }\n}\n\nimpl Error for ParsingError {\n fn description(&self) -> &str {\n self.desc.as_slice()\n }\n\n fn cause(&self) -> Option<&Error> {\n None\n }\n}\n\nimpl ParsingError {\n pub fn new(desc: String) -> Self {\n ParsingError {\n desc: desc\n }\n }\n}\n\npub type ParsingResult<T> = Result<T, ParsingError>;\n" } ]
rust
chosen
[ { "from": "system", "value": "Enable an old test that works now!\n" }, { "from": "human", "value": "use std::cell::Cell;\nuse std::rc::Rc;\nuse std::sync::Arc;\n\nfn rc_cell() -> Rc<Cell<i32>> {\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r\n}\n\n// TODO(solson): also requires destructors to run for the second borrow to work\n// TODO(solson): needs StructWrappedNullablePointer support\n// fn rc_refcell() -> i32 {\n// let r = Rc::new(RefCell::new(42));\n// *r.borrow_mut() += 10;\n// let x = *r.borrow();\n// x\n// }\n\nfn arc() -> Arc<i32> {\n let a = Arc::new(42);\n a\n}\n\nfn true_assert() {\n assert_eq!(1, 1);\n}\n\nfn main() {\n assert_eq!(*arc(), 42);\n assert_eq!(rc_cell().get(), 84);\n true_assert();\n}\n" }, { "from": "gpt", "value": "use std::cell::{Cell, RefCell};\nuse std::rc::Rc;\nuse std::sync::Arc;\n\nfn rc_cell() -> Rc<Cell<i32>> {\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r\n}\n\nfn rc_refcell() -> i32 {\n let r = Rc::new(RefCell::new(42));\n *r.borrow_mut() += 10;\n let x = *r.borrow();\n x\n}\n\nfn arc() -> Arc<i32> {\n let a = Arc::new(42);\n a\n}\n\nfn true_assert() {\n assert_eq!(1, 1);\n}\n\nfn main() {\n assert_eq!(*arc(), 42);\n assert_eq!(rc_cell().get(), 84);\n assert_eq!(rc_refcell(), 52);\n true_assert();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add example of usage tests from file `Readme.md`\n" }, { "from": "human", "value": "#![ warn( missing_docs ) ]\n#![ warn( missing_debug_implementations ) ]\n\n//!\n//! Basic exceptions handling mechanism.\n//!\n//! # Sample\n//! ```\n//! use werror::*;\n//!\n//! let err1 = Error::new( \"Some error\" );\n//! println!( \"err1 : {}\", err1 );\n//! // < err1 : Some error\n//! ```\n\nmod assert;\nmod error;\n\npub use assert::*;\npub use error::*;\n" }, { "from": "gpt", "value": "#![ warn( missing_docs ) ]\n#![ warn( missing_debug_implementations ) ]\n\n//!\n//! Basic exceptions handling mechanism.\n//!\n// //! # Sample\n// //! ```\n// //! use werror::*;\n// //!\n// //! let err1 = Error::new( \"Some error\" );\n// //! println!( \"err1 : {}\", err1 );\n// //! // < err1 : Some error\n// //! ```\n\n#![ doc = include_str!( \"../../../module/rust/werror/Readme.md\" ) ]\n\nmod assert;\nmod error;\n\npub use assert::*;\npub use error::*;\n" } ]
rust
chosen
[ { "from": "system", "value": "chore: Remove platform check for syntax-highlight\n\nNow that there is `null` syntax highlighting, let people attempt to\nenable the real version if they want to, even on unsupported platforms.\n\nReally, the motivation is I'm running into a rustfmt bug and trying to\nwork around it.\n" }, { "from": "human", "value": "#[cfg(all(feature=\"syntax-highlight\", not(windows)))]\nmod syntect;\n#[cfg(all(feature=\"syntax-highlight\", not(windows)))]\npub use self::syntect::*;\n\n#[cfg(any(not(feature=\"syntax-highlight\"), windows))]\nmod null;\n#[cfg(any(not(feature=\"syntax-highlight\"), windows))]\npub use self::null::*;\n" }, { "from": "gpt", "value": "#[cfg(feature=\"syntax-highlight\")]\nmod syntect;\n#[cfg(feature=\"syntax-highlight\")]\npub use self::syntect::*;\n\n#[cfg(not(feature=\"syntax-highlight\"))]\nmod null;\n#[cfg(not(feature=\"syntax-highlight\"))]\npub use self::null::*;\n" } ]
rust
chosen
[ { "from": "system", "value": "Simplify GistFile's read functions return types.\n" }, { "from": "human", "value": "extern crate rustc_serialize;\n\nuse self::rustc_serialize::json::{ToJson, Json};\nuse std::collections::BTreeMap;\n\nuse std::fs::File;\nuse std::io::{self, Read};\nuse std::path::Path;\n\npub struct GistFile {\n pub name: String,\n pub contents: String,\n}\n\n\nimpl GistFile {\n pub fn new(name: String) -> GistFile {\n GistFile {\n name: name,\n contents: String::new(),\n }\n }\n\n // Read standard input to contents buffer.\n pub fn read_stdin(&mut self) -> Result<usize, io::Error> {\n io::stdin().read_to_string(&mut self.contents)\n }\n\n // Read file to contents buffer.\n pub fn read_file(&mut self) -> Result<usize, io::Error> {\n let path = Path::new(&self.name);\n let mut fh = File::open(&path).unwrap();\n fh.read_to_string(&mut self.contents)\n }\n}\n\nimpl ToJson for GistFile {\n fn to_json(&self) -> Json {\n let mut root = BTreeMap::new();\n root.insert(\"content\".to_string(), self.contents.to_json());\n Json::Object(root)\n }\n}\n\n" }, { "from": "gpt", "value": "extern crate rustc_serialize;\n\nuse self::rustc_serialize::json::{ToJson, Json};\nuse std::collections::BTreeMap;\n\nuse std::fs::File;\nuse std::io::{self, Read};\nuse std::path::Path;\n\npub struct GistFile {\n pub name: String,\n pub contents: String,\n}\n\n\nimpl GistFile {\n pub fn new(name: String) -> GistFile {\n GistFile {\n name: name,\n contents: String::new(),\n }\n }\n\n // Read standard input to contents buffer.\n pub fn read_stdin(&mut self) -> io::Result<()> {\n try!(io::stdin().read_to_string(&mut self.contents));\n Ok(())\n }\n\n // Read file to contents buffer.\n pub fn read_file(&mut self) -> io::Result<()> {\n let path = Path::new(&self.name);\n let mut fh = try!(File::open(&path));\n\n try!(fh.read_to_string(&mut self.contents));\n Ok(())\n }\n}\n\nimpl ToJson for GistFile {\n fn to_json(&self) -> Json {\n let mut root = BTreeMap::new();\n root.insert(\"content\".to_string(), self.contents.to_json());\n Json::Object(root)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn read_invalid_file() {\n let mut f = GistFile::new(\"/not/found.txt\".to_string());\n assert!(f.read_file().is_err());\n }\n\n #[test]\n fn read_valid_file() {\n let mut f = GistFile::new(\"Cargo.toml\".to_string());\n assert!(f.read_file().is_ok());\n }\n\n #[test]\n fn read_closed_stdin() {\n let mut f = GistFile::new(\"Cargo.toml\".to_string());\n assert!(f.read_stdin().is_err());\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Debug print the dev syntax tree\n" }, { "from": "human", "value": "extern crate proc_macro;\n\nuse proc_macro::TokenStream;\nuse syn::{parse_macro_input, File};\n\n#[proc_macro]\npub fn r#mod(input: TokenStream) -> TokenStream {\n parse_macro_input!(input as File);\n \"fn main() {}\".parse().unwrap()\n}\n" }, { "from": "gpt", "value": "extern crate proc_macro;\n\nuse proc_macro::TokenStream;\nuse syn::{parse_macro_input, File};\n\n#[proc_macro]\npub fn r#mod(input: TokenStream) -> TokenStream {\n let file = parse_macro_input!(input as File);\n println!(\"{:#?}\", file);\n \"fn main() {}\".parse().unwrap()\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Rename JsType to JsT, JsT to JsTrait\n" }, { "from": "human", "value": "use std::cmp::Ordering;\nuse std::hash::{Hash, Hasher};\nuse uuid::Uuid;\n\npub struct JsType {\n uid: Uuid,\n t: Box<JsT>,\n}\n\nimpl JsType {\n fn new(t: Box<JsT>) -> JsType {\n JsType {\n uid: Uuid::new_v4(),\n t: t,\n }\n }\n}\n\nimpl PartialEq for JsType {\n fn eq(&self, other: &Self) -> bool {\n self.uid == other.uid\n }\n\n fn ne(&self, other: &Self) -> bool {\n !self.eq(other)\n }\n}\n\nimpl Eq for JsType{}\n\nimpl Hash for JsType {\n fn hash<H>(&self, state: &mut H) where H: Hasher {\n self.uid.hash(state);\n }\n\n fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher {\n for ref d in data {\n d.uid.hash(state);\n }\n }\n}\n\npub trait JsT {}\n" }, { "from": "gpt", "value": "use std::cmp::Ordering;\nuse std::hash::{Hash, Hasher};\nuse uuid::Uuid;\n\npub trait JsTrait {}\n\npub struct JsT {\n uid: Uuid,\n t: Box<JsTrait>,\n}\n\nimpl JsT {\n pub fn new(t: Box<JsTrait>) -> JsT {\n JsT {\n uid: Uuid::new_v4(),\n t: t,\n }\n }\n}\n\nimpl PartialEq for JsT {\n fn eq(&self, other: &Self) -> bool {\n self.uid == other.uid\n }\n\n fn ne(&self, other: &Self) -> bool {\n !self.eq(other)\n }\n}\n\nimpl Eq for JsT {}\n\nimpl Hash for JsT {\n fn hash<H>(&self, state: &mut H) where H: Hasher {\n self.uid.hash(state);\n }\n\n fn hash_slice<H>(data: &[Self], state: &mut H) where H: Hasher {\n for ref d in data {\n d.uid.hash(state);\n }\n }\n}\n\n" } ]
rust
chosen
[ { "from": "system", "value": "Return an error result, instead of pretending unimplemented commands are ok\n" }, { "from": "human", "value": "#[macro_use]\nextern crate clap;\n#[macro_use]\nextern crate log;\nextern crate git2;\n\nmod cd;\nmod cli;\nmod logger;\nmod repository;\nmod settings;\n\nuse std::process::exit;\n\nuse settings::Settings;\n\nfn main() {\n match run_cli() {\n Ok(_) => {}\n Err((message, exit_code)) => {\n error!(\"{}\", message);\n exit(exit_code);\n }\n }\n}\n\nfn run_cli() -> Result<(), (String, i32)> {\n let matches = cli::app().get_matches();\n\n let settings = Settings::from_matches(&matches);\n logger::init(&settings).expect(\"Failed to initialize logger.\");\n\n match matches.subcommand() {\n (\"cd\", Some(m)) => try!(cd::open_shell_at_repo(&settings, m)),\n (\"clone\", Some(m)) => try!(repository::clone(&settings, m)),\n (\"link\", Some(m)) => try!(repository::link_repo(&settings, m)),\n (name, _) => println!(\"'{}' is not implemented yet.\", name),\n };\n\n Ok(())\n}\n" }, { "from": "gpt", "value": "#[macro_use]\nextern crate clap;\n#[macro_use]\nextern crate log;\nextern crate git2;\n\nmod cd;\nmod cli;\nmod logger;\nmod repository;\nmod settings;\n\nuse std::process::exit;\n\nuse settings::Settings;\n\nfn main() {\n match run_cli() {\n Ok(_) => {}\n Err((message, exit_code)) => {\n error!(\"{}\", message);\n exit(exit_code);\n }\n }\n}\n\nfn run_cli() -> Result<(), (String, i32)> {\n let matches = cli::app().get_matches();\n\n let settings = Settings::from_matches(&matches);\n logger::init(&settings).expect(\"Failed to initialize logger.\");\n\n match matches.subcommand() {\n (\"cd\", Some(m)) => try!(cd::open_shell_at_repo(&settings, m)),\n (\"clone\", Some(m)) => try!(repository::clone(&settings, m)),\n (\"link\", Some(m)) => try!(repository::link_repo(&settings, m)),\n (name, _) => {\n return Err((format!(\"'{}' is not implemented yet.\", name), 1));\n }\n };\n\n Ok(())\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add derive debug to RegistryValue\n" }, { "from": "human", "value": "//! Types used in the registry.\n\nuse std::fmt::{Debug, Display, Formatter};\n\nuse std::sync::Arc;\nuse rustc_serialize::{Encodable, Decodable};\nuse rustc_serialize::json::{Json, ToJson};\n\n/// How much access things have\n#[derive(Debug, PartialEq, Eq, Clone, Copy)]\npub enum RegistryAccess {\n Public,\n Lua,\n Private\n}\n\n/// Values stored in the registry\npub struct RegistryValue {\n access: RegistryAccess,\n object: Arc<Json>\n}\n\n//#[derive(RustcSeralizeable)]\nstruct Point {\n x: u32,\n y: u32\n}\n\nimpl RegistryValue {\n\n pub fn new<T>(access: RegistryAccess, data: T) -> RegistryValue\n where T: ToJson {\n RegistryValue {\n access: access,\n object: Arc::new(data.to_json())\n }\n }\n\n /// What access the module has to it\n pub fn access(&self) -> RegistryAccess {\n self.access\n }\n\n /// Gets the json of a registry value\n pub fn get_json(&self) -> Arc<Json> {\n self.object.clone()\n }\n}\n" }, { "from": "gpt", "value": "//! Types used in the registry.\n\nuse std::fmt::{Debug, Display, Formatter};\n\nuse std::sync::Arc;\nuse rustc_serialize::{Encodable, Decodable};\nuse rustc_serialize::json::{Json, ToJson};\n\n/// How much access things have\n#[derive(Debug, PartialEq, Eq, Clone, Copy)]\npub enum RegistryAccess {\n Public,\n Lua,\n Private\n}\n\n/// Values stored in the registry\n#[derive(Debug)]\npub struct RegistryValue {\n access: RegistryAccess,\n object: Arc<Json>\n}\n\nimpl RegistryValue {\n /// Creates a new RegistryValue\n pub fn new<T>(access: RegistryAccess, data: T) -> RegistryValue\n where T: ToJson {\n RegistryValue {\n access: access,\n object: Arc::new(data.to_json())\n }\n }\n\n /// What access the module has to it\n pub fn access(&self) -> RegistryAccess {\n self.access\n }\n\n /// Gets the json of a registry value\n pub fn get_json(&self) -> Arc<Json> {\n self.object.clone()\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add tests for declare_lint_pass and impl_lint_pass\n" }, { "from": "human", "value": "#![deny(clippy::internal)]\n#![feature(rustc_private)]\n\n#[macro_use]\nextern crate rustc;\nuse rustc::lint;\n\n#[macro_use]\nextern crate clippy_lints;\n\ndeclare_clippy_lint! {\n pub TEST_LINT,\n correctness,\n \"\"\n}\n\ndeclare_clippy_lint! {\n pub TEST_LINT_REGISTERED,\n correctness,\n \"\"\n}\n\npub struct Pass;\nimpl lint::LintPass for Pass {\n fn get_lints(&self) -> lint::LintArray {\n lint_array!(TEST_LINT_REGISTERED)\n }\n\n fn name(&self) -> &'static str {\n \"TEST_LINT\"\n }\n}\n\nfn main() {}\n" }, { "from": "gpt", "value": "#![deny(clippy::internal)]\n#![feature(rustc_private)]\n\n#[macro_use]\nextern crate rustc;\nuse rustc::lint::{LintArray, LintPass};\n\n#[macro_use]\nextern crate clippy_lints;\n\ndeclare_clippy_lint! {\n pub TEST_LINT,\n correctness,\n \"\"\n}\n\ndeclare_clippy_lint! {\n pub TEST_LINT_REGISTERED,\n correctness,\n \"\"\n}\n\npub struct Pass;\nimpl LintPass for Pass {\n fn get_lints(&self) -> LintArray {\n lint_array!(TEST_LINT_REGISTERED)\n }\n\n fn name(&self) -> &'static str {\n \"TEST_LINT\"\n }\n}\n\ndeclare_lint_pass!(Pass2 => [TEST_LINT_REGISTERED]);\n\npub struct Pass3;\nimpl_lint_pass!(Pass3 => [TEST_LINT_REGISTERED]);\n\nfn main() {}\n" } ]
rust
chosen
[ { "from": "system", "value": "Convert 1mm points in test\n" }, { "from": "human", "value": "// this is just a test binary that can be hooked up to Instruments\nextern crate lonlat_bng;\nuse lonlat_bng::{convert_to_bng_threaded, Array};\n\nextern crate rand;\nuse rand::distributions::{IndependentSample, Range};\n\nextern crate libc;\n\nfn main() {\n let num_coords = 1000;\n let between_lon = Range::new(-6.379880, 1.768960);\n let between_lat = Range::new(49.871159, 55.811741);\n let mut rng = rand::thread_rng();\n let lon_vec = vec![between_lon.ind_sample(&mut rng) as f32; num_coords];\n let lat_vec = vec![between_lat.ind_sample(&mut rng) as f32; num_coords];\n let lon_arr = Array {\n data: lon_vec.as_ptr() as *const libc::c_void,\n len: lon_vec.len() as libc::size_t,\n };\n let lat_arr = Array {\n data: lat_vec.as_ptr() as *const libc::c_void,\n len: lat_vec.len() as libc::size_t,\n };\n\n convert_to_bng_threaded(lon_arr, lat_arr);\n}\n" }, { "from": "gpt", "value": "// this is just a test binary that can be hooked up to Instruments\nextern crate lonlat_bng;\nuse lonlat_bng::{convert_to_bng_threaded, Array};\n\nextern crate rand;\nuse rand::distributions::{IndependentSample, Range};\n\nextern crate libc;\n\nfn main() {\n let num_coords = 1000000;\n let between_lon = Range::new(-6.379880, 1.768960);\n let between_lat = Range::new(49.871159, 55.811741);\n let mut rng = rand::thread_rng();\n let lon_vec = vec![between_lon.ind_sample(&mut rng) as f32; num_coords];\n let lat_vec = vec![between_lat.ind_sample(&mut rng) as f32; num_coords];\n let lon_arr = Array {\n data: lon_vec.as_ptr() as *const libc::c_void,\n len: lon_vec.len() as libc::size_t,\n };\n let lat_arr = Array {\n data: lat_vec.as_ptr() as *const libc::c_void,\n len: lat_vec.len() as libc::size_t,\n };\n\n convert_to_bng_threaded(lon_arr, lat_arr);\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add a commented-out RefCell test.\n" }, { "from": "human", "value": "#![feature(custom_attribute, box_syntax)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn rc_cell() -> i32 {\n use std::rc::Rc;\n use std::cell::Cell;\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r.get()\n}\n\n#[miri_run]\nfn arc() -> i32 {\n use std::sync::Arc;\n let a = Arc::new(42);\n *a\n}\n\n#[miri_run]\nfn true_assert() {\n assert_eq!(1, 1);\n}\n" }, { "from": "gpt", "value": "#![feature(custom_attribute, box_syntax)]\n#![allow(dead_code, unused_attributes)]\n\n#[miri_run]\nfn rc_cell() -> i32 {\n use std::rc::Rc;\n use std::cell::Cell;\n let r = Rc::new(Cell::new(42));\n let x = r.get();\n r.set(x + x);\n r.get()\n}\n\n// TODO(tsion): borrow code needs to evaluate string statics via Lvalue::Static\n// #[miri_run]\n// fn rc_refcell() -> i32 {\n// use std::rc::Rc;\n// use std::cell::RefCell;\n// let r = Rc::new(RefCell::new(42));\n// *r.borrow_mut() += 10;\n// let x = *r.borrow();\n// x\n// }\n\n#[miri_run]\nfn arc() -> i32 {\n use std::sync::Arc;\n let a = Arc::new(42);\n *a\n}\n\n#[miri_run]\nfn true_assert() {\n assert_eq!(1, 1);\n}\n" } ]
rust
chosen
[ { "from": "human", "value": "Refactor the ConstantOrigin shape to the query module.\n" }, { "from": "gpt", "value": "use na::{RealField, Unit};\n\nuse crate::math::{Isometry, Point, Vector};\nuse crate::shape::SupportMap;\n\n/// A support mapping that is always equal to the origin, independently from its transform.\npub struct ConstantOrigin;\n\nimpl<N: RealField> SupportMap<N> for ConstantOrigin {\n #[inline]\n fn support_point(&self, _: &Isometry<N>, _: &Vector<N>) -> Point<N> {\n Point::origin()\n }\n\n #[inline]\n fn support_point_toward(&self, _: &Isometry<N>, _: &Unit<Vector<N>>) -> Point<N> {\n Point::origin()\n }\n}\n\n/// The Minkowski sum of a shape and a ball.\npub struct DilatedShape<'a, N: RealField, S: ?Sized + SupportMap<N>> {\n /// The shape involved in the Minkowski sum.\n pub shape: &'a S,\n /// The radius of the ball involved in the Minkoski sum.\n pub radius: N,\n}\n\nimpl<'a, N: RealField, S: ?Sized + SupportMap<N>> SupportMap<N> for DilatedShape<'a, N, S> {\n #[inline]\n fn support_point(&self, m: &Isometry<N>, dir: &Vector<N>) -> Point<N> {\n self.support_point_toward(m, &Unit::new_normalize(*dir))\n }\n\n #[inline]\n fn support_point_toward(&self, m: &Isometry<N>, dir: &Unit<Vector<N>>) -> Point<N> {\n self.shape.support_point_toward(m, dir) + **dir * self.radius\n }\n}" } ]
rust
chosen
[ { "from": "system", "value": "Move reexport to the other reexports\n" }, { "from": "human", "value": "//! Provides types and functions related to working with PostgreSQL\n//!\n//! Much of this module is re-exported from database agnostic locations.\n//! However, if you are writing code specifically to extend Diesel on\n//! PostgreSQL, you may need to work with this module directly.\n\npub mod expression;\npub mod types;\n\n#[doc(hidden)]\n#[cfg(feature = \"with-deprecated\")]\n#[deprecated(since = \"2.0.0\", note = \"Use `diesel::upsert` instead\")]\npub use crate::upsert;\n\nmod backend;\nmod connection;\nmod metadata_lookup;\npub(crate) mod query_builder;\npub(crate) mod serialize;\nmod transaction;\nmod value;\n\npub use self::backend::{Pg, PgTypeMetadata};\npub use self::connection::PgConnection;\npub use self::metadata_lookup::PgMetadataLookup;\npub use self::query_builder::DistinctOnClause;\npub use self::query_builder::PgQueryBuilder;\npub use self::transaction::TransactionBuilder;\npub use self::value::PgValue;\n\n/// Data structures for PG types which have no corresponding Rust type\n///\n/// Most of these types are used to implement `ToSql` and `FromSql` for higher\n/// level types.\npub mod data_types {\n #[doc(inline)]\n pub use super::types::date_and_time::{PgDate, PgInterval, PgTime, PgTimestamp};\n #[doc(inline)]\n pub use super::types::floats::PgNumeric;\n #[doc(inline)]\n pub use super::types::money::PgMoney;\n pub use super::types::money::PgMoney as Cents;\n}\n" }, { "from": "gpt", "value": "//! Provides types and functions related to working with PostgreSQL\n//!\n//! Much of this module is re-exported from database agnostic locations.\n//! However, if you are writing code specifically to extend Diesel on\n//! PostgreSQL, you may need to work with this module directly.\n\npub mod expression;\npub mod types;\n\nmod backend;\nmod connection;\nmod metadata_lookup;\npub(crate) mod query_builder;\npub(crate) mod serialize;\nmod transaction;\nmod value;\n\npub use self::backend::{Pg, PgTypeMetadata};\npub use self::connection::PgConnection;\npub use self::metadata_lookup::PgMetadataLookup;\npub use self::query_builder::DistinctOnClause;\npub use self::query_builder::PgQueryBuilder;\npub use self::transaction::TransactionBuilder;\npub use self::value::PgValue;\n#[doc(hidden)]\n#[cfg(feature = \"with-deprecated\")]\n#[deprecated(since = \"2.0.0\", note = \"Use `diesel::upsert` instead\")]\npub use crate::upsert;\n\n/// Data structures for PG types which have no corresponding Rust type\n///\n/// Most of these types are used to implement `ToSql` and `FromSql` for higher\n/// level types.\npub mod data_types {\n #[doc(inline)]\n pub use super::types::date_and_time::{PgDate, PgInterval, PgTime, PgTimestamp};\n #[doc(inline)]\n pub use super::types::floats::PgNumeric;\n #[doc(inline)]\n pub use super::types::money::PgMoney;\n pub use super::types::money::PgMoney as Cents;\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Remove unused StoreTrue from example\n" }, { "from": "human", "value": "extern crate tvdb;\nextern crate argparse;\n\nuse argparse::{ArgumentParser, StoreTrue, Store};\n\n\nfn main(){\n let mut series_name = \"\".to_owned();\n let mut season_no = 1;\n let mut episode_no = 1;\n\n {\n let mut ap = ArgumentParser::new();\n ap.refer(&mut series_name).add_argument(\"series\", Store, \"Series name\");\n ap.refer(&mut season_no).add_argument(\"season\", Store, \"Season number\");\n ap.refer(&mut episode_no).add_argument(\"episode\", Store, \"Episode number\");\n ap.parse_args_or_exit();\n }\n\n // Construct API object\n let api = tvdb::Tvdb::new(\"0629B785CE550C8D\");\n\n // Search for series\n let sr = api.search(&series_name, \"en\").ok().unwrap();\n\n // Loop over found series\n for r in sr.iter(){\n // Print: \"Series Name\" (id: 12345)\n println!(\"{:?} (id: {})\", r.seriesname, r.seriesid);\n\n // Get episode information\n println!(\"{:?}\", api.episode(&sr[0], season_no, episode_no));\n }\n}\n" }, { "from": "gpt", "value": "extern crate tvdb;\nextern crate argparse;\n\nuse argparse::{ArgumentParser, Store};\n\n\nfn main(){\n let mut series_name = \"\".to_owned();\n let mut season_no = 1;\n let mut episode_no = 1;\n\n {\n let mut ap = ArgumentParser::new();\n ap.refer(&mut series_name).add_argument(\"series\", Store, \"Series name\");\n ap.refer(&mut season_no).add_argument(\"season\", Store, \"Season number\");\n ap.refer(&mut episode_no).add_argument(\"episode\", Store, \"Episode number\");\n ap.parse_args_or_exit();\n }\n\n // Construct API object\n let api = tvdb::Tvdb::new(\"0629B785CE550C8D\");\n\n // Search for series\n let sr = api.search(&series_name, \"en\").ok().unwrap();\n\n // Loop over found series\n for r in sr.iter(){\n // Print: \"Series Name\" (id: 12345)\n println!(\"{:?} (id: {})\", r.seriesname, r.seriesid);\n\n // Get episode information\n println!(\"{:?}\", api.episode(&sr[0], season_no, episode_no));\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Write a test file to generated directory\n" }, { "from": "human", "value": "extern crate syn;\n\nuse syn::DeriveInput;\n\npub fn generate_elm(_: &DeriveInput) {\n // do nothing\n}\n" }, { "from": "gpt", "value": "extern crate syn;\n\nuse std::env;\nuse std::fs::File;\nuse std::io::{Write, BufWriter};\nuse syn::DeriveInput;\n\npub fn generate_elm(_: &DeriveInput) {\n let mut path = env::current_dir().unwrap();\n path.push(\"generated/test.txt\");\n\n let file = File::create(path).unwrap();\n let ref mut w = BufWriter::new(file);\n w.write(\"Hello, World!\".as_bytes()).unwrap();\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make the error stack type public\n" }, { "from": "human", "value": "pub enum ErrorLevel {\n Info,\n Warning,\n Error,\n}\n\n// Use a hashmap which contains an error level and a string\ntype ErrorStack = Vec<(ErrorLevel, String)>;" }, { "from": "gpt", "value": "pub enum ErrorLevel {\n Info,\n Warning,\n Error,\n}\n\n// Use a hashmap which contains an error level and a string\npub type ErrorStack = Vec<(ErrorLevel, String)>;" } ]
rust
chosen
[ { "from": "system", "value": "Define `OscMessage` and `OscBundle` structs\n" }, { "from": "human", "value": "use errors;\n\n// see OSC Type Tag String: http://opensoundcontrol.org/spec-1_0\n// padding: zero bytes (n*4)\npub enum OscType {\n OscInt(i32),\n OscFloat(f32),\n OscString(String),\n OscBlob(Vec<u8>),\n OscTime(u32, u32),\n // nonstandard argument types\n // ignore them if not implemented\n OscLong(i64),\n OscDouble(f64),\n OscChar(u8),\n OscColor(u32), // byte-order: RGBA\n OscMidi(OscMidiType),\n OscTrue,\n OscFalse,\n OscNil,\n OscInf,\n OscArray(Vec<OscType>),\n}\n\npub struct OscMidiType {\n port: u8,\n status: u8,\n data1: u8, // maybe use an enum for data?\n data2: u8,\n}\n\n/// An *osc packet* can contain an *osc message* or a bundle of nested messages\n/// which is called *osc bundle*.\npub enum OscPacket {\n Message(OscMessage),\n Bundle(OscBundle),\n}\n\npub struct OscMessage;\npub struct OscBundle;\n\npub type OscResult<T> = Result<T, errors::OscError>;" }, { "from": "gpt", "value": "use errors;\n\n// see OSC Type Tag String: http://opensoundcontrol.org/spec-1_0\n// padding: zero bytes (n*4)\npub enum OscType {\n OscInt(i32),\n OscFloat(f32),\n OscString(String),\n OscBlob(Vec<u8>),\n OscTime(u32, u32),\n // nonstandard argument types\n // ignore them if not implemented\n OscLong(i64),\n OscDouble(f64),\n OscChar(u8),\n OscColor(u32), // byte-order: RGBA\n OscMidi(OscMidiType),\n OscTrue,\n OscFalse,\n OscNil,\n OscInf,\n OscArray(Vec<OscType>),\n}\n\npub struct OscMidiType {\n port: u8,\n status: u8,\n data1: u8, // maybe use an enum for data?\n data2: u8,\n}\n\n/// An *osc packet* can contain an *osc message* or a bundle of nested messages\n/// which is called *osc bundle*.\npub enum OscPacket {\n Message(OscMessage),\n Bundle(OscBundle),\n}\n\npub struct OscMessage {\n pub addr: String,\n pub args: Option<Vec<OscType>>,\n}\n\npub struct OscBundle {\n pub timetag: OscType,\n pub content: Vec<OscPacket>,\n}\n\npub type OscResult<T> = Result<T, errors::OscError>;" } ]
rust
chosen
[ { "from": "system", "value": "Rewrite the FPE test to not use Context directly\n" }, { "from": "human", "value": "// This file is part of libfringe, a low-level green threading library.\n// Copyright (c) Ben Segall <talchas@gmail.com>\n// Copyright (c) edef <edef@edef.eu>\n// See the LICENSE file included in this distribution.\n#![cfg(target_os = \"linux\")]\n#![feature(test)]\n#![feature(thread_local)]\n#![feature(asm)]\nextern crate fringe;\nextern crate test;\nuse fringe::Context;\nuse test::black_box;\n\n#[thread_local]\nstatic mut ctx_slot: *mut Context<fringe::OsStack> = 0 as *mut Context<_>;\n\nconst FE_DIVBYZERO: i32 = 0x4;\nextern {\n fn feenableexcept(except: i32) -> i32;\n}\n\n#[test]\n#[ignore]\nfn fpe() {\n unsafe extern \"C\" fn universe_destroyer(_arg: usize) -> ! {\n loop {\n println!(\"{:?}\", 1.0/black_box(0.0));\n Context::swap(ctx_slot, ctx_slot, 0);\n }\n }\n\n unsafe {\n let stack = fringe::OsStack::new(4 << 20).unwrap();\n let mut ctx = Context::new(stack, universe_destroyer);\n ctx_slot = &mut ctx;\n\n Context::swap(ctx_slot, ctx_slot, 0);\n feenableexcept(FE_DIVBYZERO);\n Context::swap(ctx_slot, ctx_slot, 0);\n }\n}\n" }, { "from": "gpt", "value": "// This file is part of libfringe, a low-level green threading library.\n// Copyright (c) Ben Segall <talchas@gmail.com>\n// Copyright (c) edef <edef@edef.eu>\n// See the LICENSE file included in this distribution.\n#![cfg(target_os = \"linux\")]\n#![feature(test)]\n#![feature(thread_local)]\n#![feature(asm)]\nextern crate fringe;\nextern crate test;\nuse fringe::{OsStack, Generator};\nuse test::black_box;\n\nconst FE_DIVBYZERO: i32 = 0x4;\nextern {\n fn feenableexcept(except: i32) -> i32;\n}\n\n#[test]\n#[ignore]\nfn fpe() {\n let stack = OsStack::new(0).unwrap();\n let mut gen = Generator::new(stack, move |yielder| {\n yielder.generate(1.0 / black_box(0.0));\n });\n\n unsafe { feenableexcept(FE_DIVBYZERO); }\n println!(\"{:?}\", gen.next());\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Test fix: Ensuring db cleanup doesn't happen until after test completion...\n" }, { "from": "human", "value": "// Copyright 2014 Tyler Neely\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//\nextern crate rocksdb;\nmod util;\n\nuse rocksdb::{DB, Options};\nuse util::DBPath;\n\n#[test]\nfn test_set_num_levels() {\n let n = DBPath::new(\"_rust_rocksdb_test_set_num_levels\");\n {\n let mut opts = Options::default();\n opts.create_if_missing(true);\n opts.set_num_levels(2);\n let _db = DB::open(&opts, n).unwrap();\n }\n}\n" }, { "from": "gpt", "value": "// Copyright 2014 Tyler Neely\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//\nextern crate rocksdb;\nmod util;\n\nuse rocksdb::{DB, Options};\nuse util::DBPath;\n\n#[test]\nfn test_set_num_levels() {\n let n = DBPath::new(\"_rust_rocksdb_test_set_num_levels\");\n {\n let mut opts = Options::default();\n opts.create_if_missing(true);\n opts.set_num_levels(2);\n let _db = DB::open(&opts, &n).unwrap();\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Support for the new constraint.\n" }, { "from": "human", "value": "use traits::Grid;\nuse traits::Engine;\nuse traits::Consumer;\n\n\npub struct Sequential<G: Grid, C: Consumer> {\n grid: G,\n consumer: C\n}\n\nimpl<G: Grid, C: Consumer> Sequential<G, C> {\n\n pub fn new(grid: G, consumer: C) -> Self {\n Sequential {\n grid: grid,\n consumer: consumer\n }\n }\n}\n\n\nimpl<G: Grid, C: Consumer> Engine for Sequential<G, C> {\n fn run_times(&mut self, times: i64) {\n for _ in 0..times {\n self.grid.step();\n self.consumer.consume(&self.grid);\n }\n }\n}" }, { "from": "gpt", "value": "use traits::Cell;\nuse traits::Consumer;\nuse traits::Grid;\nuse traits::Engine;\n\n\npub struct Sequential<C: Cell, G: Grid<Cell=C>, Con: Consumer<Cell=C>> {\n grid: G,\n consumer: Con\n}\n\nimpl<C: Cell, G: Grid<Cell=C>, Con: Consumer<Cell=C>> Sequential<C, G, Con> {\n\n pub fn new(grid: G, consumer: Con) -> Self {\n Sequential {\n grid: grid,\n consumer: consumer\n }\n }\n}\n\n\nimpl<C: Cell, G: Grid<Cell=C>, Con: Consumer<Cell=C>> Engine for Sequential<C, G, Con> {\n fn run_times(&mut self, times: i64) {\n for _ in 0..times {\n self.grid.step();\n self.consumer.consume(&self.grid);\n }\n }\n}" } ]
rust
chosen
[ { "from": "system", "value": "Correct pointer size cfg variables\n" }, { "from": "human", "value": "pub trait Key: Copy + PartialEq + Ord + Default {\n type Bytes: AsRef<[u8]>;\n fn into_bytes(self) -> Self::Bytes;\n fn from_bytes(bytes: Self::Bytes) -> Self;\n}\n\n\nmacro_rules! impl_key {\n ($type:ident, $size:expr) => {\n impl Key for $type {\n type Bytes = [u8; $size];\n fn into_bytes(self) -> Self::Bytes {\n unsafe {\n ::std::mem::transmute(self.to_be())\n }\n }\n\n fn from_bytes(bytes: Self::Bytes) -> Self {\n let integer = unsafe {\n ::std::mem::transmute(bytes)\n };\n $type::from_be(integer)\n }\n }\n }\n}\n\nimpl_key!(u8, 1);\nimpl_key!(u16, 2);\nimpl_key!(u32, 4);\nimpl_key!(u64, 8);\n#[cfg(feature = \"i128\")]\nimpl_key!(u128, 16);\n#[cfg(target_pointer_size = \"64\")]\nimpl_key!(usize, 8);\n#[cfg(target_pointer_size = \"32\")]\nimpl_key!(usize, 4);\n" }, { "from": "gpt", "value": "pub trait Key: Copy + PartialEq + Ord + Default {\n type Bytes: AsRef<[u8]>;\n fn into_bytes(self) -> Self::Bytes;\n fn from_bytes(bytes: Self::Bytes) -> Self;\n}\n\n\nmacro_rules! impl_key {\n ($type:ident, $size:expr) => {\n impl Key for $type {\n type Bytes = [u8; $size];\n fn into_bytes(self) -> Self::Bytes {\n unsafe {\n ::std::mem::transmute(self.to_be())\n }\n }\n\n fn from_bytes(bytes: Self::Bytes) -> Self {\n let integer = unsafe {\n ::std::mem::transmute(bytes)\n };\n $type::from_be(integer)\n }\n }\n }\n}\n\nimpl_key!(u8, 1);\nimpl_key!(u16, 2);\nimpl_key!(u32, 4);\nimpl_key!(u64, 8);\n#[cfg(feature = \"i128\")]\nimpl_key!(u128, 16);\n#[cfg(target_pointer_width = \"32\")]\nimpl_key!(usize, 4);\n#[cfg(target_pointer_width = \"64\")]\nimpl_key!(usize, 8);\n" } ]
rust
chosen
[ { "from": "system", "value": "Change incrementor to be more generic\n" }, { "from": "human", "value": "use std::cell::Cell;\n\npub trait Incrementor {\n fn increment(&self);\n}\n\nimpl Incrementor for Cell<u8> {\n fn increment(&self) {\n self.set(self.get() + 1);\n }\n}\n\nimpl Incrementor for Cell<u16> {\n fn increment(&self) {\n self.set(self.get() + 1);\n }\n}\n" }, { "from": "gpt", "value": "use std::cell::Cell;\nuse std::num::One;\n\npub trait Incrementor {\n fn increment(&self);\n}\n\nimpl<T: Copy + Num> Incrementor for Cell<T> {\n fn increment(&self) {\n self.set(self.get() + One::one());\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Break out of loop if can't send data\n\nFixes #4046\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//! A task that sniffs data\nuse std::comm::{channel, Receiver, Sender, Disconnected};\nuse std::task::TaskBuilder;\nuse resource_task::{LoadResponse};\n\npub type SnifferTask = Sender<LoadResponse>;\n\npub fn new_sniffer_task(next_rx: Sender<LoadResponse>) -> SnifferTask {\n let (sen, rec) = channel();\n let builder = TaskBuilder::new().named(\"SnifferManager\");\n builder.spawn(proc() {\n SnifferManager::new(rec).start(next_rx);\n });\n sen\n}\n\nstruct SnifferManager {\n data_receiver: Receiver<LoadResponse>,\n}\n\nimpl SnifferManager {\n fn new(data_receiver: Receiver<LoadResponse>) -> SnifferManager {\n SnifferManager {\n data_receiver: data_receiver,\n }\n }\n}\n\nimpl SnifferManager {\n fn start(&self, next_rx: Sender<LoadResponse>) {\n loop {\n match self.data_receiver.try_recv() {\n Ok(snif_data) => next_rx.send(snif_data),\n Err(Disconnected) => break,\n Err(_) => (),\n }\n }\n }\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\n//! A task that sniffs data\nuse std::comm::{channel, Receiver, Sender, Disconnected};\nuse std::task::TaskBuilder;\nuse resource_task::{LoadResponse};\n\npub type SnifferTask = Sender<LoadResponse>;\n\npub fn new_sniffer_task(next_rx: Sender<LoadResponse>) -> SnifferTask {\n let (sen, rec) = channel();\n let builder = TaskBuilder::new().named(\"SnifferManager\");\n builder.spawn(proc() {\n SnifferManager::new(rec).start(next_rx);\n });\n sen\n}\n\nstruct SnifferManager {\n data_receiver: Receiver<LoadResponse>,\n}\n\nimpl SnifferManager {\n fn new(data_receiver: Receiver<LoadResponse>) -> SnifferManager {\n SnifferManager {\n data_receiver: data_receiver,\n }\n }\n}\n\nimpl SnifferManager {\n fn start(self, next_rx: Sender<LoadResponse>) {\n loop {\n match self.data_receiver.try_recv() {\n Ok(snif_data) => {\n let result = next_rx.send_opt(snif_data);\n if result.is_err() {\n break;\n }\n }\n Err(Disconnected) => break,\n Err(_) => (),\n }\n }\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Make RepositoryList and its field public\n" }, { "from": "human", "value": "use std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\nuse toml::Value as Toml;\n\nuse error::PackageError;\nuse package::Package;\n\n/// The struct which represents the repos.\n#[derive(Deserialize)]\npub struct Repository {\n url: String,\n packages: Vec<Package>,\n}\n\n/// Struct which represents a list of Repositories.\n#[derive(Deserialize)]\nstruct RepositoryList(Vec<Repository>);\n\nimpl Repository {\n /// Returns the URL of the Repository.\n pub fn url(&self) -> &str {\n &self.url\n }\n\n /// Returns the packages which are provided by the Repository.\n pub fn packages(&self) -> &[Package] {\n self.packages.as_slice()\n }\n\n // Attempts to find the package which satifies the predicate.\n // If there are no packages that match the predicate, a `None` is returned.\n pub fn find_by_predicate<F>(&self, predicate: F) -> Option<&Package> \n where F: Fn(&Package) -> bool {\n for pkg in &self.packages {\n if predicate(&pkg) {\n return Some(&pkg)\n }\n };\n\n None\n }\n}\n\nimpl RepositoryList {\n fn read_from(path: &Path) -> Result<Self, PackageError> {\n let mut list = File::open(path)?;\n let mut content = String::new();\n list.read_to_string(&mut content)?;\n let list = content.parse::<Toml>()?;\n let list = list.try_into::<Self>()?;\n Ok(list)\n }\n}" }, { "from": "gpt", "value": "use std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\nuse toml::Value as Toml;\n\nuse error::PackageError;\nuse package::Package;\n\n/// The struct which represents the repos.\n#[derive(Deserialize)]\npub struct Repository {\n url: String,\n packages: Vec<Package>,\n}\n\n/// Struct which represents a list of Repositories.\n#[derive(Deserialize)]\npub struct RepositoryList(pub Vec<Repository>);\n\nimpl Repository {\n /// Returns the URL of the Repository.\n pub fn url(&self) -> &str {\n &self.url\n }\n\n /// Returns the packages which are provided by the Repository.\n pub fn packages(&self) -> &[Package] {\n self.packages.as_slice()\n }\n\n // Attempts to find the package which satifies the predicate.\n // If there are no packages that match the predicate, a `None` is returned.\n pub fn find_by_predicate<F>(&self, predicate: F) -> Option<&Package> \n where F: Fn(&Package) -> bool {\n for pkg in &self.packages {\n if predicate(&pkg) {\n return Some(&pkg)\n }\n };\n\n None\n }\n}\n\nimpl RepositoryList {\n fn read_from(path: &Path) -> Result<Self, PackageError> {\n let mut list = File::open(path)?;\n let mut content = String::new();\n list.read_to_string(&mut content)?;\n let list = content.parse::<Toml>()?;\n let list = list.try_into::<Self>()?;\n Ok(list)\n }\n}" } ]
rust
chosen
[ { "from": "system", "value": "Check if empty after normalization\n" }, { "from": "human", "value": "#![feature(slice_concat_ext)]\n\nuse unicode_segmentation::UnicodeSegmentation;\nuse std::slice::SliceConcatExt;\n\nextern crate unicode_segmentation;\n\npub fn normalize_tag(tag: &str) -> Result<String, &'static str> {\n\n if tag.is_empty() {\n Err(\"Tag is empty\")\n } else {\n let lc = tag.to_lowercase();\n let words: Vec<&str> = lc.unicode_words().collect();\n let joined = words.join(\"-\");\n Ok(joined)\n }\n}\n\n#[test]\nfn test_tag_normalize() {\n assert!(normalize_tag(\"\").is_err());\n assert_eq!(Ok(\"abc\".to_string()), normalize_tag(\"ABC\"));\n assert_eq!(Ok(\"abc-this-is-a-tag\".to_string()), normalize_tag(\"ABC this is a tag\\\"\"));\n assert_eq!(Ok(\"abc-this-is-a-tag\".to_string()), normalize_tag(\" ABC this is a tag\\\"\"));\n assert_eq!(Ok(\"abc-this-is-a-tag\".to_string()), normalize_tag(\"-- ABC this is a tag--\\\"\"));\n}\n" }, { "from": "gpt", "value": "#![feature(slice_concat_ext)]\n\nuse unicode_segmentation::UnicodeSegmentation;\nuse std::slice::SliceConcatExt;\n\nextern crate unicode_segmentation;\n\npub fn normalize_tag(tag: &str) -> Result<String, &'static str> {\n if tag.is_empty() {\n Err(\"Tag is empty\")\n } else {\n let lc = tag.to_lowercase();\n let words: Vec<&str> = lc.unicode_words().collect();\n let joined = words.join(\"-\");\n if joined.is_empty() {\n Err(\"Tag is empty after normalization\")\n } else {\n Ok(joined)\n }\n }\n}\n\n#[test]\nfn test_tag_normalize() {\n assert!(normalize_tag(\"\").is_err());\n assert_eq!(Ok(\"abc\".to_string()), normalize_tag(\"ABC\"));\n assert_eq!(Ok(\"abc-this-is-a-tag\".to_string()), normalize_tag(\"ABC this is a tag\\\"\"));\n assert_eq!(Ok(\"abc-this-is-a-tag\".to_string()), normalize_tag(\" ABC this is a tag\\\"\"));\n assert_eq!(Ok(\"abc-this-is-a-tag\".to_string()), normalize_tag(\"-- ABC this is a tag--\\\"\"));\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Allow `non_snake_case` in the generated code.\n" }, { "from": "human", "value": "#![feature(plugin_registrar, quote)]\nextern crate rustc;\nextern crate syntax;\n\nuse rustc::plugin::Registry;\nuse syntax::ast::TokenTree;\nuse syntax::codemap::Span;\nuse syntax::ext::base::{ExtCtxt, MacItems, MacResult};\nuse syntax::parse::tts_to_parser;\n\nmod block;\nmod parser;\nmod generator;\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n reg.register_macro(\"speculate\", expand_speculate);\n}\n\nfn expand_speculate(cx: &mut ExtCtxt, _sp: Span, tokens: &[TokenTree]) -> Box<MacResult + 'static> {\n let mut parser = tts_to_parser(cx.parse_sess(), tokens.to_vec(), cx.cfg());\n let blocks = parser::parse(&mut parser);\n let items = blocks.iter().map(|p| {\n generator::generate(cx, p)\n }).collect::<Vec<_>>();\n\n let module = quote_item!(cx,\n mod sup {\n $items\n }\n ).expect(\"failed to create item!\");\n\n MacItems::new(Some(module).into_iter())\n}\n" }, { "from": "gpt", "value": "#![feature(plugin_registrar, quote)]\nextern crate rustc;\nextern crate syntax;\n\nuse rustc::plugin::Registry;\nuse syntax::ast::TokenTree;\nuse syntax::codemap::Span;\nuse syntax::ext::base::{ExtCtxt, MacItems, MacResult};\nuse syntax::parse::tts_to_parser;\n\nmod block;\nmod parser;\nmod generator;\n\n#[plugin_registrar]\npub fn plugin_registrar(reg: &mut Registry) {\n reg.register_macro(\"speculate\", expand_speculate);\n}\n\nfn expand_speculate(cx: &mut ExtCtxt, _sp: Span, tokens: &[TokenTree]) -> Box<MacResult + 'static> {\n let mut parser = tts_to_parser(cx.parse_sess(), tokens.to_vec(), cx.cfg());\n let blocks = parser::parse(&mut parser);\n let items = blocks.iter().map(|p| {\n generator::generate(cx, p)\n }).collect::<Vec<_>>();\n\n let module = quote_item!(cx,\n #[allow(non_snake_case)]\n mod sup {\n $items\n }\n ).expect(\"failed to create item!\");\n\n MacItems::new(Some(module).into_iter())\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add feature annotations for currently unstable features used\n" }, { "from": "human", "value": "#[macro_use] extern crate log;\nextern crate \"rustc-serialize\" as rustc_serialize;\n\npub mod hpack;\npub mod http;\npub mod client;\n\nmod tests {\n}\n" }, { "from": "gpt", "value": "#![feature(io, net, core, std_misc)]\n\n#[macro_use] extern crate log;\nextern crate \"rustc-serialize\" as rustc_serialize;\n\npub mod hpack;\npub mod http;\npub mod client;\n\nmod tests {\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Use std::rt::io::Timer instead of an unsafe sleep()\n" }, { "from": "human", "value": "/*!\n * Hello World server in Rust\n * Binds REP socket to tcp://*:5555\n * Expects \"Hello\" from client, replies with \"World\"\n */\n\nextern mod zmq;\n\nuse std::libc;\n\nfn main() {\n#[fixed_stack_segment];\n\n let context = zmq::Context::new();\n let responder = context.socket(zmq::REP).unwrap();\n\n assert!(responder.bind(\"tcp://*:5555\").is_ok());\n\n let mut msg = zmq::Message::new();\n loop {\n responder.recv(&mut msg, 0);\n do msg.with_str |s| {\n printfln!(\"Received %s\", s);\n }\n responder.send_str(\"World\", 0);\n unsafe { libc::sleep(1); }\n }\n}\n" }, { "from": "gpt", "value": "/*!\n * Hello World server in Rust\n * Binds REP socket to tcp://*:5555\n * Expects \"Hello\" from client, replies with \"World\"\n */\n\nextern mod zmq;\n\nuse std::rt;\n\nfn main() {\n#[fixed_stack_segment];\n\n let context = zmq::Context::new();\n let responder = context.socket(zmq::REP).unwrap();\n\n assert!(responder.bind(\"tcp://*:5555\").is_ok());\n\n let mut msg = zmq::Message::new();\n loop {\n responder.recv(&mut msg, 0);\n do msg.with_str |s| {\n printfln!(\"Received %s\", s);\n }\n responder.send_str(\"World\", 0);\n let timer = ~rt::io::Timer::new();\n do timer.map_move |mut t| { t.sleep(1) };\n }\n}\n" } ]
rust
chosen
[ { "from": "system", "value": "Add new type for an URL\n" }, { "from": "human", "value": "extern crate hyper;\nextern crate pbr;\nextern crate ansi_term;\n\nuse std::sync::{Arc, Mutex};\n\n#[macro_use]\npub mod logs;\n\npub mod authorization;\npub mod cargo_helper;\npub mod client;\npub mod contentlength;\npub mod download;\npub mod filesize;\npub mod http_version;\npub mod response;\npub mod util;\npub mod write;\n\n/// Represents a number of bytes, as `u64`.\npub type Bytes = u64;\n/// Represents a 'chunk', which is just a piece of bytes.\ntype Chunk = Vec<u8>;\n/// Represents a list of chunks\npub type Chunks = Vec<Chunk>;\n/// Represents a shared mutable reference of chunks\npub type SChunks = Arc<Mutex<Chunks>>;\n" }, { "from": "gpt", "value": "extern crate hyper;\nextern crate pbr;\nextern crate ansi_term;\n\nuse std::sync::{Arc, Mutex};\n\n#[macro_use]\npub mod logs;\n\npub mod authorization;\npub mod cargo_helper;\npub mod client;\npub mod contentlength;\npub mod download;\npub mod filesize;\npub mod http_version;\npub mod response;\npub mod util;\npub mod write;\n\n/// Represents a number of bytes, as `u64`.\npub type Bytes = u64;\n/// Represents a 'chunk', which is just a piece of bytes.\ntype Chunk = Vec<u8>;\n/// Represents a list of chunks\npub type Chunks = Vec<Chunk>;\n/// Represents a shared mutable reference of chunks\npub type SChunks = Arc<Mutex<Chunks>>;\n/// Represents an URL\npub type URL<'a> = &'a str;\n" } ]
rust
chosen
[ { "from": "system", "value": "Change BufferID type -> String\n" }, { "from": "human", "value": "//! This is the `custom types` module for Xtensis.\n\n// This file is part of Xtensis.\n\n// This is the Xtensis text editor; it edits text.\n// Copyright (C) 2016-2017 The Xtensis Developers\n\n// This program is free software: you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see\n// <http://www.gnu.org/licenses/>.\n\n/// ID of a Buffer.\npub type BufferID = usize;\n" }, { "from": "gpt", "value": "//! This is the `custom types` module for Xtensis.\n\n// This file is part of Xtensis.\n\n// This is the Xtensis text editor; it edits text.\n// Copyright (C) 2016-2017 The Xtensis Developers\n\n// This program is free software: you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n// General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see\n// <http://www.gnu.org/licenses/>.\n\n/// ID of a Buffer.\npub type BufferID = String,\n" } ]
rust
chosen
[ { "from": "system", "value": "Add test for trait check in prelude collision lint.\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\n// See https://github.com/rust-lang/rust/issues/86633\nfn main() {\n let s = S;\n let s2 = s.try_into();\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\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" } ]
rust
chosen