Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add test cases for outer attributes on all item types
// xfail-stage0 #[attr = "val"] mod mod1 { } fn main() { }
// xfail-stage0 #[attr = "val"] const int x = 10; #[attr = "val"] mod mod1 { } #[attr = "val"] native "rust" mod rustrt { } #[attr = "val"] type t = obj { }; #[attr = "val"] obj o() { } fn main() { }
Use the no-field syntax instead of empty braces.
#![feature(asm, alloc_error_handler, core_intrinsics, lang_items, naked_functions)] #![no_std] extern crate alloc; mod callback; pub mod adc; pub mod ble_composer; pub mod ble_parser; pub mod buttons; pub mod console; pub mod debug; pub mod electronics; pub mod gpio; pub mod led; pub mod result; pub mod sensors; pub mod shared_memory; pub mod simple_ble; pub mod temperature; pub mod timer; pub mod unwind_symbols; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] pub mod entry_point; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] mod lang_items; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] pub mod syscalls; #[cfg(not(any(target_arch = "arm", target_arch = "riscv32")))] #[path = "syscalls_mock.rs"] mod syscalls; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] #[global_allocator] static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty(); // Dummy structure to force importing the panic_handler and other no_std elements when nothing else // is imported. pub struct LibTock {}
#![feature(asm, alloc_error_handler, core_intrinsics, lang_items, naked_functions)] #![no_std] extern crate alloc; mod callback; pub mod adc; pub mod ble_composer; pub mod ble_parser; pub mod buttons; pub mod console; pub mod debug; pub mod electronics; pub mod gpio; pub mod led; pub mod result; pub mod sensors; pub mod shared_memory; pub mod simple_ble; pub mod temperature; pub mod timer; pub mod unwind_symbols; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] pub mod entry_point; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] mod lang_items; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] pub mod syscalls; #[cfg(not(any(target_arch = "arm", target_arch = "riscv32")))] #[path = "syscalls_mock.rs"] mod syscalls; #[cfg(any(target_arch = "arm", target_arch = "riscv32"))] #[global_allocator] static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty(); // Dummy structure to force importing the panic_handler and other no_std elements when nothing else // is imported. pub struct LibTock;
Use camel case key for desired state.
use std::collections::HashMap; use rustc_serialize::json; use schema::{UnitOption, UnitStates}; use fleet::FleetAPI; pub struct Client { fleet: FleetAPI, } impl Client { pub fn new(root_url: &'static str) -> Client { Client { fleet: FleetAPI::new(root_url) } } pub fn create_unit( &self, name: &'static str, desired_state: UnitStates, options: Vec<UnitOption> ) -> Result<(), &str> { let options_json = json::encode(&options).unwrap(); let mut body = HashMap::new(); body.insert("desired_state", desired_state.to_json()); body.insert("options", &options_json); self.fleet.put_units(name, &json::encode(&body).unwrap()) } } #[cfg(test)] mod client_tests { use super::Client; use schema::UnitStates; #[test] fn it_can_be_constructed() { Client::new("http://localhost"); } #[test] fn it_can_create_units() { let client = Client::new("http://it_can_create_units.example.com"); let result = client.create_unit("example.service", UnitStates::Launched, vec![]); assert!(result.is_ok()) } }
use std::collections::HashMap; use rustc_serialize::json; use schema::{UnitOption, UnitStates}; use fleet::FleetAPI; pub struct Client { fleet: FleetAPI, } impl Client { pub fn new(root_url: &'static str) -> Client { Client { fleet: FleetAPI::new(root_url) } } pub fn create_unit( &self, name: &'static str, desired_state: UnitStates, options: Vec<UnitOption> ) -> Result<(), &str> { let options_json = json::encode(&options).unwrap(); let mut body = HashMap::new(); body.insert("desiredState", desired_state.to_json()); body.insert("options", &options_json); self.fleet.put_units(name, &json::encode(&body).unwrap()) } } #[cfg(test)] mod client_tests { use super::Client; use schema::UnitStates; #[test] fn it_can_be_constructed() { Client::new("http://localhost"); } #[test] fn it_can_create_units() { let client = Client::new("http://it_can_create_units.example.com"); let result = client.create_unit("example.service", UnitStates::Launched, vec![]); assert!(result.is_ok()) } }
Use an existing graph implementation
#[cfg(test)] mod tests { #[test] fn it_works() { } }
// http://smallcultfollowing.com/babysteps/blog/2015/04/06/modeling-graphs-in-rust-using-vector-indices/ pub struct Graph { nodes: Vec<NodeData>, edges: Vec<EdgeData>, } impl Graph { pub fn add_node(&mut self) -> NodeIndex { let index = self.nodes.len(); self.nodes.push(NodeData { first_outgoing_edge: None }); index } pub fn add_edge(&mut self, source: NodeIndex, target: NodeIndex) { let edge_index = self.edges.len(); let node_data = &mut self.nodes[source]; self.edges.push(EdgeData { target: target, next_outgoing_edge: node_data.first_outgoing_edge }); node_data.first_outgoing_edge = Some(edge_index); } pub fn successors(&self, source: NodeIndex) -> Successors { let first_outgoing_edge = self.nodes[source].first_outgoing_edge; Successors { graph: self, current_edge_index: first_outgoing_edge } } pub fn print(self) { for n in 0..self.nodes.len() { print!("Node {} goes to: ", n); let mut suc = self.successors(n); loop { match suc.next() { Some(s) => { print!("{}, ", s) }, None => { print!("\n"); break }, } } } } } pub struct Successors<'graph> { graph: &'graph Graph, current_edge_index: Option<EdgeIndex>, } impl<'graph> Iterator for Successors<'graph> { type Item = NodeIndex; fn next(&mut self) -> Option<NodeIndex> { match self.current_edge_index { None => None, Some(edge_num) => { let edge = &self.graph.edges[edge_num]; self.current_edge_index = edge.next_outgoing_edge; Some(edge.target) } } } } pub type NodeIndex = usize; pub struct NodeData { first_outgoing_edge: Option<EdgeIndex>, } pub type EdgeIndex = usize; pub struct EdgeData { target: NodeIndex, next_outgoing_edge: Option<EdgeIndex> } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let mut g = Graph { nodes: vec![], edges: vec![] }; let node0 = g.add_node(); let node1 = g.add_node(); let node2 = g.add_node(); let node3 = g.add_node(); g.add_edge(node0, node1); g.add_edge(node0, node2); g.add_edge(node2, node1); g.add_edge(node2, node3); g.print(); } }
Add a test for syntax like: ..t.s
// run-pass // Test that functional record update/struct update syntax works inside // a closure when the feature `capture_disjoint_fields` is enabled. #![feature(capture_disjoint_fields)] //~^ WARNING: the feature `capture_disjoint_fields` is incomplete //~| NOTE: `#[warn(incomplete_features)]` on by default //~| NOTE: see issue #53488 <https://github.com/rust-lang/rust/issues/53488> struct S { a: String, b: String, } fn main() { let a = String::new(); let b = String::new(); let s = S {a, b}; let c = || { let s2 = S { a: format!("New a"), ..s }; println!("{} {}", s2.a, s2.b); }; c(); }
// run-pass // Test that functional record update/struct update syntax works inside // a closure when the feature `capture_disjoint_fields` is enabled. #![feature(capture_disjoint_fields)] //~^ WARNING: the feature `capture_disjoint_fields` is incomplete //~| NOTE: `#[warn(incomplete_features)]` on by default //~| NOTE: see issue #53488 <https://github.com/rust-lang/rust/issues/53488> #[derive(Clone)] struct S { a: String, b: String, } struct T { a: String, s: S, } fn main() { let a = String::new(); let b = String::new(); let c = String::new(); let s = S {a, b}; let t = T { a: c, s: s.clone() }; let c = || { let s2 = S { a: format!("New s2"), ..s }; let s3 = S { a: format!("New s3"), ..t.s }; println!("{} {}", s2.a, s2.b); println!("{} {} {}", s3.a, s3.b, t.a); }; c(); }
Return 404 on missing static file in todo example.
use rocket::response::NamedFile; use std::io; use std::path::{Path, PathBuf}; #[get("/<path..>", rank = 5)] fn all(path: PathBuf) -> io::Result<NamedFile> { NamedFile::open(Path::new("static/").join(path)) }
use std::path::{Path, PathBuf}; use rocket::response::NamedFile; #[get("/<path..>", rank = 5)] fn all(path: PathBuf) -> Option<NamedFile> { NamedFile::open(Path::new("static/").join(path)).ok() }
Rewrite the FPE test to not use Context directly
// This file is part of libfringe, a low-level green threading library. // Copyright (c) Ben Segall <talchas@gmail.com> // Copyright (c) Nathan Zadoks <nathan@nathan7.eu> // See the LICENSE file included in this distribution. #![cfg(target_os = "linux")] #![feature(test)] #![feature(thread_local)] #![feature(asm)] extern crate fringe; extern crate test; use fringe::Context; use test::black_box; #[thread_local] static mut ctx_slot: *mut Context<fringe::OsStack> = 0 as *mut Context<_>; const FE_DIVBYZERO: i32 = 0x4; extern { fn feenableexcept(except: i32) -> i32; } #[test] #[ignore] fn fpe() { unsafe extern "C" fn universe_destroyer(_arg: usize) -> ! { loop { println!("{:?}", 1.0/black_box(0.0)); Context::swap(ctx_slot, ctx_slot, 0); } } unsafe { let stack = fringe::OsStack::new(4 << 20).unwrap(); let mut ctx = Context::new(stack, universe_destroyer); ctx_slot = &mut ctx; Context::swap(ctx_slot, ctx_slot, 0); feenableexcept(FE_DIVBYZERO); Context::swap(ctx_slot, ctx_slot, 0); } }
// This file is part of libfringe, a low-level green threading library. // Copyright (c) Ben Segall <talchas@gmail.com> // Copyright (c) Nathan Zadoks <nathan@nathan7.eu> // See the LICENSE file included in this distribution. #![cfg(target_os = "linux")] #![feature(test)] #![feature(thread_local)] #![feature(asm)] extern crate fringe; extern crate test; use fringe::{OsStack, Generator}; use test::black_box; const FE_DIVBYZERO: i32 = 0x4; extern { fn feenableexcept(except: i32) -> i32; } #[test] #[ignore] fn fpe() { let stack = OsStack::new(0).unwrap(); let mut gen = Generator::new(stack, move |yielder| { yielder.generate(1.0 / black_box(0.0)); }); unsafe { feenableexcept(FE_DIVBYZERO); } println!("{:?}", gen.next()); }
Use a plain map and avoid copying
extern crate yaml_rust; use self::yaml_rust::{YamlLoader, Yaml}; pub fn from_yaml(yaml_file: String) -> Vec<String> { let docs = YamlLoader::load_from_str(&yaml_file).unwrap(); let doc = &docs[0]; let key = Yaml::from_str("default"); let default_command_list = doc.as_hash().unwrap().get(&key).unwrap(); let yaml_commands = default_command_list.as_vec().unwrap(); let mut result_commands = Vec::new(); result_commands.extend( yaml_commands.iter().map(|e| element.as_str().unwrap().to_string() ) result_commands }
extern crate yaml_rust; use self::yaml_rust::{YamlLoader, Yaml}; pub fn from_yaml(yaml_file: String) -> Vec<String> { let docs = YamlLoader::load_from_str(&yaml_file).unwrap(); let doc = &docs[0]; let key = Yaml::from_str("default"); let default_command_list = doc.as_hash().unwrap().get(&key).unwrap(); let yaml_commands = default_command_list.as_vec().unwrap(); yaml_commands.iter() .map(|e| e.as_str().expect("expected string").to_string()) .collect::<Vec<_>>() }
Use const instead of static for global constants
extern crate wechat; use wechat::WeChatClient; static APPID: &'static str = "wxd7aa56e2c7b1f4f1"; static SECRET: &'static str = "2817b66a1d5829847196cf2f96ab2816"; #[test] fn test_fetch_access_token() { let mut client = WeChatClient::new(APPID, SECRET); let access_token = client.fetch_access_token(); assert!(access_token.is_some()); assert!(!client.access_token.is_empty()); } #[test] fn test_call_api_with_no_access_token_provided() { let mut client = WeChatClient::new(APPID, SECRET); let res = client.get("getcallbackip", vec![]); let data = match res { Ok(data) => data, Err(_) => { panic!("Error calling API"); }, }; let ip_list = data.find("ip_list").unwrap(); let ips = ip_list.as_array().unwrap(); assert!(ips.len() > 0); }
extern crate wechat; use wechat::WeChatClient; const APPID: &'static str = "wxd7aa56e2c7b1f4f1"; const SECRET: &'static str = "2817b66a1d5829847196cf2f96ab2816"; #[test] fn test_fetch_access_token() { let mut client = WeChatClient::new(APPID, SECRET); let access_token = client.fetch_access_token(); assert!(access_token.is_some()); assert!(!client.access_token.is_empty()); } #[test] fn test_call_api_with_no_access_token_provided() { let mut client = WeChatClient::new(APPID, SECRET); let res = client.get("getcallbackip", vec![]); let data = match res { Ok(data) => data, Err(_) => { panic!("Error calling API"); }, }; let ip_list = data.find("ip_list").unwrap(); let ips = ip_list.as_array().unwrap(); assert!(ips.len() > 0); }
Refactor to make the task look like the other gtk related tasks
extern crate gtk; use gtk::prelude::*; use std::ops::Not; use std::sync::{Arc, RwLock}; fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let window = gtk::Window::new(gtk::WindowType::Toplevel); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); let button = gtk::Button::new_with_label("Hello World! "); window.add(&button); let lock = Arc::new(RwLock::new(false)); let lock_button = lock.clone(); button.connect_clicked(move |_| { let mut reverse = lock_button.write().unwrap(); *reverse = reverse.not(); }); let lock_thread = lock.clone(); gtk::timeout_add(100, move || { let reverse = lock_thread.read().unwrap(); let mut text = button.get_label().unwrap(); let len = &text.len(); if *reverse { let begin = &text.split_off(1); text.insert_str(0, begin); } else { let end = &text.split_off(len - 1); text.insert_str(0, end); } button.set_label(&text); gtk::Continue(true) }); window.show_all(); gtk::main(); }
#[cfg(feature = "gtk")] mod graphical { extern crate gtk; use self::gtk::traits::*; use self::gtk::{Inhibit, Window, WindowType}; use std::ops::Not; use std::sync::{Arc, RwLock}; pub fn create_window() { gtk::init().expect("Failed to initialize GTK"); let window = Window::new(WindowType::Toplevel); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); let button = gtk::Button::new_with_label("Hello World! "); window.add(&button); let lock = Arc::new(RwLock::new(false)); let lock_button = lock.clone(); button.connect_clicked(move |_| { let mut reverse = lock_button.write().unwrap(); *reverse = reverse.not(); }); let lock_thread = lock.clone(); gtk::timeout_add(100, move || { let reverse = lock_thread.read().unwrap(); let mut text = button.get_label().unwrap(); let len = &text.len(); if *reverse { let begin = &text.split_off(1); text.insert_str(0, begin); } else { let end = &text.split_off(len - 1); text.insert_str(0, end); } button.set_label(&text); gtk::Continue(true) }); window.show_all(); gtk::main(); } } #[cfg(feature = "gtk")] fn main() { graphical::create_window(); } #[cfg(not(feature = "gtk"))] fn main() {}
Use num_seqs == 1 to decide if min and max need initialisation
extern crate bio; use std::io; use std::cmp; use bio::io::fasta; fn main() { let reader = fasta::Reader::new(io::stdin()); let mut num_seqs = 0; let mut total = 0; let mut max_len = 0; let mut min_len = 0; let mut this_len; let mut first_seq = true; println!("FILENAME\tTOTAL\tNUMSEQ\tMIN\tAVG\tMAX"); for next in reader.records() { match next { Ok(record) => { num_seqs += 1; this_len = record.seq().len(); total += this_len; max_len = cmp::max(max_len, this_len); if first_seq { min_len = this_len; first_seq = false; } else { min_len = cmp::min(min_len, this_len); } }, Err(error) => println!("{}", error), } } if num_seqs > 0 { let average = ((total as f64) / (num_seqs as f64)).floor() as usize; println!("{}\t{}\t{}\t{}\t{}", num_seqs, total, min_len, average, max_len); } else { println!("0\t0\t-\t-\t-"); } }
extern crate bio; use std::io; use std::cmp; use bio::io::fasta; fn main() { let reader = fasta::Reader::new(io::stdin()); let mut num_seqs = 0; let mut total = 0; let mut max_len = 0; let mut min_len = 0; let mut this_len; println!("FILENAME\tTOTAL\tNUMSEQ\tMIN\tAVG\tMAX"); for next in reader.records() { match next { Ok(record) => { num_seqs += 1; this_len = record.seq().len(); total += this_len; if num_seqs == 1 { max_len = this_len; min_len = this_len; } else { max_len = cmp::max(max_len, this_len); min_len = cmp::min(min_len, this_len); } }, Err(error) => println!("{}", error), } } if num_seqs > 0 { let average = ((total as f64) / (num_seqs as f64)).floor() as usize; println!("{}\t{}\t{}\t{}\t{}", num_seqs, total, min_len, average, max_len); } else { println!("0\t0\t-\t-\t-"); } }
Add spec links for ui properties
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> // CSS Basic User Interface Module Level 1 // https://drafts.csswg.org/css-ui-3/ <% data.new_style_struct("UI", inherited=False, gecko_name="UIReset") %> ${helpers.single_keyword("ime-mode", "normal auto active disabled inactive", products="gecko", gecko_ffi_name="mIMEMode", animatable=False)} ${helpers.single_keyword("-moz-user-select", "auto text none all", products="gecko", gecko_ffi_name="mUserSelect", gecko_enum_prefix="StyleUserSelect", gecko_inexhaustive=True, animatable=False)}
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> // CSS Basic User Interface Module Level 1 // https://drafts.csswg.org/css-ui-3/ <% data.new_style_struct("UI", inherited=False, gecko_name="UIReset") %> // TODO spec says that UAs should not support this // we should probably remove from gecko (https://bugzilla.mozilla.org/show_bug.cgi?id=1328331) ${helpers.single_keyword("ime-mode", "normal auto active disabled inactive", products="gecko", gecko_ffi_name="mIMEMode", animatable=False, spec="https://drafts.csswg.org/css-ui/#input-method-editor")} ${helpers.single_keyword("-moz-user-select", "auto text none all", products="gecko", gecko_ffi_name="mUserSelect", gecko_enum_prefix="StyleUserSelect", gecko_inexhaustive=True, animatable=False, spec="https://drafts.csswg.org/css-ui-4/#propdef-user-select")}
Add a unit test to ensure that ctypes are imported
//! This is a very early work-in-progress binding to various Linux Kernel APIs. //! //! It is not yet ready for use in your projects. Once version 0.1 or higher //! is released, you are welcome to start using it :) #![cfg(target_os="linux")] pub use std::os::*; pub use std::os::raw::*;
//! This is a very early work-in-progress binding to various Linux Kernel APIs. //! //! It is not yet ready for use in your projects. Once version 0.1 or higher //! is released, you are welcome to start using it :) #![cfg(target_os="linux")] pub use std::os::*; pub use std::os::raw::*; #[cfg(test)] mod tests { #[allow(unused_variables)] #[test] fn ensure_types_exist() { let schar: ::c_schar = -3; let uchar: ::c_uchar = 2; let achar: ::c_char = 62; let ashort: ::c_short = -5162; let ushort: ::c_ushort = 65000; let aint: ::c_int = 26327; let uint: ::c_uint = 20000026; let long: ::c_long = 75473765327; let ulong: ::c_ulong = 26294762868676748; let float: ::c_float = 2462347.426f32; let double: ::c_double = 2694237684327.4326237637f64; assert!(true);//Well, we haven't crashed! I guess it worked } }
Use XML lexer for HTML documents.
use std::path::Path; #[derive(Debug, PartialEq)] pub enum Type { CoffeeScript, JavaScript, JSON, XML, Ruby, Rust, ERB } pub fn from_path(path: &Path) -> Option<Type> { match path.to_str() { Some(filename) => { let extension = filename.split('.').last(); match extension { Some("coffee") => Some(Type::CoffeeScript), Some("js") => Some(Type::JavaScript), Some("json") => Some(Type::JSON), Some("xml") => Some(Type::XML), Some("rake") => Some(Type::Ruby), Some("rb") => Some(Type::Ruby), Some("rs") => Some(Type::Rust), Some("erb") => Some(Type::ERB), _ => None, } }, None => return None, } } #[cfg(test)] mod tests { use std::path::Path; use super::from_path; use super::Type; #[test] fn from_path_works() { let buffer_type = from_path(&Path::new("file.json")).unwrap(); assert_eq!(buffer_type, Type::JSON); } }
use std::path::Path; #[derive(Debug, PartialEq)] pub enum Type { CoffeeScript, JavaScript, JSON, XML, Ruby, Rust, ERB } pub fn from_path(path: &Path) -> Option<Type> { match path.to_str() { Some(filename) => { let extension = filename.split('.').last(); match extension { Some("coffee") => Some(Type::CoffeeScript), Some("js") => Some(Type::JavaScript), Some("json") => Some(Type::JSON), Some("html") => Some(Type::XML), Some("xml") => Some(Type::XML), Some("rake") => Some(Type::Ruby), Some("rb") => Some(Type::Ruby), Some("rs") => Some(Type::Rust), Some("erb") => Some(Type::ERB), _ => None, } }, None => return None, } } #[cfg(test)] mod tests { use std::path::Path; use super::from_path; use super::Type; #[test] fn from_path_works() { let buffer_type = from_path(&Path::new("file.json")).unwrap(); assert_eq!(buffer_type, Type::JSON); } }
Move back to stable rust
//! Iota //! //! A highly customisable text editor built with modern hardware in mind. //! //! This module contains all you need to create an `iota` executable. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![warn(missing_docs)] #![feature(concat_idents)] #![feature(stmt_expr_attributes)] #[cfg(feature="syntax-highlighting")] extern crate syntect; extern crate rustbox; extern crate gapbuffer; extern crate tempdir; extern crate regex; extern crate unicode_width; #[macro_use] extern crate lazy_static; pub use editor::Editor; pub use input::Input; pub use frontends::RustboxFrontend; pub use modes::{StandardMode, NormalMode, Mode}; mod input; mod utils; mod buffer; mod editor; mod keyboard; mod keymap; mod view; mod uibuf; mod log; mod frontends; mod modes; mod overlay; mod command; mod textobject; mod iterators;
//! Iota //! //! A highly customisable text editor built with modern hardware in mind. //! //! This module contains all you need to create an `iota` executable. #![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![warn(missing_docs)] #[cfg(feature="syntax-highlighting")] extern crate syntect; extern crate rustbox; extern crate gapbuffer; extern crate tempdir; extern crate regex; extern crate unicode_width; #[macro_use] extern crate lazy_static; pub use editor::Editor; pub use input::Input; pub use frontends::RustboxFrontend; pub use modes::{StandardMode, NormalMode, Mode}; mod input; mod utils; mod buffer; mod editor; mod keyboard; mod keymap; mod view; mod uibuf; mod log; mod frontends; mod modes; mod overlay; mod command; mod textobject; mod iterators;
Update check target with current expected localization
use casile::*; use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; static BIN_NAME: &str = "casile"; #[test] fn outputs_version() -> Result<()> { let mut cmd = Command::cargo_bin(BIN_NAME)?; cmd.arg("--version"); cmd.assert().stdout(predicate::str::starts_with("casile v")); Ok(()) } #[test] fn ouput_is_localized() -> Result<()> { let mut cmd = Command::cargo_bin(BIN_NAME)?; cmd.arg("-l").arg("tr").arg("setup"); cmd.assert().stderr(predicate::str::contains("kurun artık")); Ok(()) } #[test] fn setup_path_exists() -> Result<()> { let mut cmd = Command::cargo_bin(BIN_NAME)?; cmd.arg("-p").arg("not_a_dir").arg("setup"); cmd.assert() .failure() .stderr(predicate::str::contains("No such file or directory")); Ok(()) } // #[test] // fn fail_on_casile_sources() -> Result<()> { // let mut cmd = Command::cargo_bin(BIN_NAME)?; // cmd.arg("-p").arg("./").arg("setup"); // cmd.assert() // .failure() // .stderr(predicate::str::contains("Make failed to parse or execute")); // Ok(()) // }
use casile::*; use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; static BIN_NAME: &str = "casile"; #[test] fn outputs_version() -> Result<()> { let mut cmd = Command::cargo_bin(BIN_NAME)?; cmd.arg("--version"); cmd.assert().stdout(predicate::str::starts_with("casile v")); Ok(()) } #[test] fn ouput_is_localized() -> Result<()> { let mut cmd = Command::cargo_bin(BIN_NAME)?; cmd.arg("-l").arg("tr").arg("setup"); cmd.assert() .stderr(predicate::str::contains("yapılandırılıyor")); Ok(()) } #[test] fn setup_path_exists() -> Result<()> { let mut cmd = Command::cargo_bin(BIN_NAME)?; cmd.arg("-p").arg("not_a_dir").arg("setup"); cmd.assert() .failure() .stderr(predicate::str::contains("No such file or directory")); Ok(()) } // #[test] // fn fail_on_casile_sources() -> Result<()> { // let mut cmd = Command::cargo_bin(BIN_NAME)?; // cmd.arg("-p").arg("./").arg("setup"); // cmd.assert() // .failure() // .stderr(predicate::str::contains("Make failed to parse or execute")); // Ok(()) // }
Remove needless lifetimes in create_post signature
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_codegen; extern crate dotenv; pub mod schema; pub mod models; use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use dotenv::dotenv; use std::env; use models::NewPost; pub fn establish_connection() -> SqliteConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); SqliteConnection::establish(&database_url) .expect(&format!("Error connecting to {}", database_url)) } pub fn create_post<'a>(conn: &SqliteConnection, title: &'a str, body: &'a str) -> usize { use schema::posts; let new_post = NewPost { title: title, body: body, }; diesel::insert(&new_post) .into(posts::table) .execute(conn) .expect("Error saving new post") }
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_codegen; extern crate dotenv; pub mod schema; pub mod models; use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use dotenv::dotenv; use std::env; use models::NewPost; pub fn establish_connection() -> SqliteConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); SqliteConnection::establish(&database_url) .expect(&format!("Error connecting to {}", database_url)) } pub fn create_post(conn: &SqliteConnection, title: &str, body: &str) -> usize { use schema::posts; let new_post = NewPost { title: title, body: body, }; diesel::insert(&new_post) .into(posts::table) .execute(conn) .expect("Error saving new post") }
Use NUM_JOBS to control make -j
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::process::Command; use std::env; fn main() { assert!(Command::new("make") .args(&["-R", "-f", "makefile.cargo"]) .status() .unwrap() .success()); println!("cargo:rustc-flags=-L native={}", env::var("OUT_DIR").unwrap()); }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::process::Command; use std::env; fn main() { assert!(Command::new("make") .args(&["-R", "-f", "makefile.cargo", &format!("-j{}", env::var("NUM_JOBS").unwrap())]) .status() .unwrap() .success()); println!("cargo:rustc-flags=-L native={}", env::var("OUT_DIR").unwrap()); }
Change starts-with, ends-with and contains builtin descriptions
use super::Status; use crate as ion_shell; use builtins_proc::builtin; macro_rules! string_function { (#[$outer:meta], $method:tt) => { #[$outer] pub fn $method(args: &[small::String], _shell: &mut crate::Shell<'_>) -> Status { if args.len() <= 2 { return Status::bad_argument(concat!( "ion: ", stringify!($method), ": two arguments must be supplied", )); } args[2..].iter().any(|arg| args[1].$method(arg.as_str())).into() } }; } string_function!( #[builtin( desc = "check if a given string starts with another one", man = " SYNOPSIS starts_with <PATTERN> tests... DESCRIPTION Returns 0 if any argument starts_with contains the first argument, else returns 0" )], starts_with); string_function!( #[builtin( desc = "check if a given string starts with another one", man = " SYNOPSIS starts_with <PATTERN> tests... DESCRIPTION Returns 0 if any argument starts_with contains the first argument, else returns 0" )], ends_with); string_function!( #[builtin( desc = "check if a given string starts with another one", man = " SYNOPSIS starts_with <PATTERN> tests... DESCRIPTION Returns 0 if any argument starts_with contains the first argument, else returns 0" )], contains);
use super::Status; use crate as ion_shell; use builtins_proc::builtin; macro_rules! string_function { (#[$outer:meta], $method:tt) => { #[$outer] pub fn $method(args: &[small::String], _shell: &mut crate::Shell<'_>) -> Status { if args.len() <= 2 { return Status::bad_argument(concat!( "ion: ", stringify!($method), ": two arguments must be supplied", )); } args[2..].iter().any(|arg| args[1].$method(arg.as_str())).into() } }; } string_function!( #[builtin( desc = "check if a given string starts with another one", man = " SYNOPSIS starts-with <PATTERN> tests... DESCRIPTION Returns 0 if the first argument starts with any other argument, else returns 0" )], starts_with); string_function!( #[builtin( desc = "check if a given string ends with another one", man = " SYNOPSIS ends-with <PATTERN> tests... DESCRIPTION Returns 0 if the first argument ends with any other argument, else returns 0" )], ends_with); string_function!( #[builtin( desc = "check if a given string contains another one", man = " SYNOPSIS contains <PATTERN> tests... DESCRIPTION Returns 0 if the first argument contains any other argument, else returns 0" )], contains);
Update example for new plugin.
#![feature(plugin)] #[plugin] extern crate compile_msg; #[cfg(rare)] compile_note!("only emitted with --cfg rate"); fn main() { compile_note!("useful information: ", 1, " instance"); compile_warning!("x"); compile_error!("y"); // compilation stops here compile_fatal!("z"); compile_note!("not emitted") }
#![feature(plugin)] #![plugin(compile_msg)] #[cfg(rare)] compile_note!("only emitted with --cfg rate"); fn main() { compile_note!("useful information: ", 1, " instance"); compile_warning!("x"); compile_error!("y"); // compilation stops here compile_fatal!("z"); compile_note!("not emitted") }
Add a user defined atom
#[derive(Clone, Debug, PartialEq)] pub enum Atom { Nil, True, False, } #[derive(Clone, Debug, PartialEq)] pub enum Term { Atom(Atom), Integer(i64), }
#[derive(Clone, Debug, PartialEq)] pub enum Atom { Nil, True, False, UserDefined(String) } #[derive(Clone, Debug, PartialEq)] pub enum Term { Atom(Atom), Integer(i64), }
Add a test for casts of univariant C-like enums
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] enum X { A = 0 as isize } enum Y { A = X::A as isize } fn main() { }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] enum X { A = 42 as isize } enum Y { A = X::A as isize } fn main() { let x = X::A; let x = x as isize; assert_eq!(x, 42); assert_eq!(Y::A as isize, 42); }
Add some proper high level tests
extern crate mtl; extern crate libc; use mtl::sys::{MTLCopyAllDevices,MTLOrigin, MTLOriginMake, MTLClearColorMake}; #[test] fn it_works() { let _origin = MTLOriginMake(50, 21, 11); let _color = MTLClearColorMake(50.0, 21.0, 11.0, 100.0); let _hi = unsafe { MTLCopyAllDevices() }; }
extern crate mtl; extern crate libc; use mtl::{Device}; #[test] fn get_device() { let device = Device::system_default_device(); assert!(device.is_ok()); } #[test] fn get_device_name() { let device = Device::system_default_device().unwrap(); assert!(!device.name().into_owned().is_empty()); }
Fix `deprecated` attribute for `__error`
// DragonFlyBSD's __error function is declared with "static inline", so it must // be implemented in the libc crate, as a pointer to a static thread_local. f! { #[deprecated(since = "0.2.77", "Use `__errno_location()` instead")] pub fn __error() -> *mut ::c_int { &mut errno } } extern "C" { #[thread_local] pub static mut errno: ::c_int; }
// DragonFlyBSD's __error function is declared with "static inline", so it must // be implemented in the libc crate, as a pointer to a static thread_local. f! { #[deprecated(since = "0.2.77", note = "Use `__errno_location()` instead")] pub fn __error() -> *mut ::c_int { &mut errno } } extern "C" { #[thread_local] pub static mut errno: ::c_int; }
Update to newest cfg conditions
//#![warn(missing_doc)] #![allow(dead_code)] #![allow(unused_variables)] #![forbid(non_camel_case_types)] #![forbid(unsafe_code)] //! This crate currently provides an almost XML 1.0/1.1-compliant pull parser. #[cfg(test)] #[macro_use] extern crate doc_comment; #[cfg(test)] doctest!("../Readme.md"); pub use reader::EventReader; pub use reader::ParserConfig; pub use writer::EventWriter; pub use writer::EmitterConfig; pub mod macros; pub mod name; pub mod attribute; pub mod common; pub mod escape; pub mod namespace; pub mod reader; pub mod writer; mod util;
//#![warn(missing_doc)] #![allow(dead_code)] #![allow(unused_variables)] #![forbid(non_camel_case_types)] #![forbid(unsafe_code)] //! This crate currently provides an almost XML 1.0/1.1-compliant pull parser. #[cfg(doctest)] #[macro_use] extern crate doc_comment; #[cfg(doctest)] doctest!("../Readme.md"); pub use reader::EventReader; pub use reader::ParserConfig; pub use writer::EventWriter; pub use writer::EmitterConfig; pub mod macros; pub mod name; pub mod attribute; pub mod common; pub mod escape; pub mod namespace; pub mod reader; pub mod writer; mod util;
Use new API in test code
extern crate txtpic; use txtpic::calculate_string_brightness::calculate_string_brightness; fn main() { println!("{}", calculate_string_brightness("@")); println!("{}", calculate_string_brightness("%")); println!("{}", calculate_string_brightness("#")); println!("{}", calculate_string_brightness("x")); println!("{}", calculate_string_brightness("+")); println!("{}", calculate_string_brightness("=")); println!("{}", calculate_string_brightness(":")); println!("{}", calculate_string_brightness("-")); println!("{}", calculate_string_brightness(".")); println!("{}", calculate_string_brightness(" ")); }
extern crate txtpic; use txtpic::calculate_string_brightness::calculate_string_brightness; fn main() { println!("{}", calculate_string_brightness('M')); println!("{}", calculate_string_brightness('@')); println!("{}", calculate_string_brightness('%')); println!("{}", calculate_string_brightness('#')); println!("{}", calculate_string_brightness('x')); println!("{}", calculate_string_brightness('+')); println!("{}", calculate_string_brightness('=')); println!("{}", calculate_string_brightness(':')); println!("{}", calculate_string_brightness('-')); println!("{}", calculate_string_brightness('.')); println!("{}", calculate_string_brightness(' ')); }
Fix tests of module `derive_tools`, test with valid features
use super::*; mod basic_test; #[ cfg( any( feature = "derive_clone_dyn" ) ) ] mod clone_dyn_test;
use super::*; mod basic_test; #[ cfg( any( feature = "derive_clone_dyn_use_std", feature = "derive_clone_dyn_use_alloc" ) ) ] mod clone_dyn_test;
Add Modbus::receive(), but this function segfaults
use errors::*; use libc::{c_char, c_int}; use libmodbus_sys; use modbus::Modbus; /// The server is waiting for request from clients and must answer when it is concerned by the request. /// The libmodbus offers the following functions to handle requests: pub trait ModbusServer { } impl ModbusServer for Modbus { }
use errors::*; use libc::{c_char, c_int}; use libmodbus_sys; use modbus::Modbus; /// The server is waiting for request from clients and must answer when it is concerned by the request. The libmodbus offers the following functions to handle requests: /// /// * Receive /// - [`receive()`](struct.Modbus.html#method.receive) /// * Reply /// - [`reply()`](struct.Modbus.html#method.reply), [`reply_exception()`](struct.Modbus.html#method.reply_exception) /// pub trait ModbusServer { fn receive(&self, request: &mut [u8]) -> Result<i32>; } impl ModbusServer for Modbus { /// `receive` - receive an indication request /// /// The [`receive()`](#method.receive) function shall receive an indication request from the socket of the context ctx. /// This function is used by Modbus slave/server to receive and analyze indication request sent by the masters/clients. /// /// If you need to use another socket or file descriptor than the one defined in the context ctx, see the function [`set_socket()`](struct.Modbus.html#method.set_socket). /// /// # Examples /// /// ``` /// use libmodbus_rs::{Modbus, ModbusServer, ModbusTCP, MODBUS_MAX_ADU_LENGTH}; /// /// let modbus = Modbus::new_tcp("127.0.0.1", 1502).unwrap(); /// let mut query = vec![0; MODBUS_MAX_ADU_LENGTH as usize]; /// /// assert!(modbus.receive(&mut query).is_ok()); /// ``` fn receive(&self, request: &mut [u8]) -> Result<i32> { unsafe { let len = libmodbus_sys::modbus_receive(self.ctx, request.as_mut_ptr()); match len { -1 => Err("Could not receive an idication request".into()), len => Ok(len), } } } }
Update primary example to use the it! macro
#[macro_use] extern crate descriptor; extern crate expector; use std::time::Duration; use std::thread::sleep; use descriptor::*; use expector::*; fn main() { describe("example group 1", source_location!(), |eg| { eg.it("1", source_location!(), || { expect(1).to(eq(2)); }); eg.it("2", source_location!(), || { expect("abc").to(eq("def")); }); eg.it("3", source_location!(), || { expect(None).to(eq(Some(3))); }); eg.it("works", source_location!(), || { }); }); describe("example group 2", source_location!(), |eg| { eg.it("17", source_location!(), || { }); eg.it("does a lot of hard work", source_location!(), || { sleep(Duration::new(3, 0)); }); }); descriptor_main(); }
#[macro_use] extern crate descriptor; extern crate expector; use std::time::Duration; use std::thread::sleep; use descriptor::*; use expector::*; fn main() { describe("example group 1", source_location!(), |eg| { it!(eg, "1", || { expect(1).to(eq(2)); }); it!(eg, "2", || { expect("abc").to(eq("def")); }); it!(eg, "3", || { expect(None).to(eq(Some(3))); }); it!(eg, "works", || { }); }); describe("example group 2", source_location!(), |eg| { it!(eg, "17", || { }); it!(eg, "does a lot of hard work", || { sleep(Duration::new(3, 0)); }); }); descriptor_main(); }
Revert "Do not require pkgconfig to succeed"
extern crate pkg_config; fn main() { match pkg_config::find_library("portaudio-2.0") { Ok(..) => {}, Err(e) => println!("Cloud not find pkg-config ({})", e), } }
extern crate pkg_config; fn main() { match pkg_config::find_library("portaudio-2.0") { Ok(..) => {}, Err(e) => panic!("{}", e), } }
Add docs on public modules
//! Provides token definitions for HTML stream processing. The goal of this //! library is to provide a simple API over which higher abstraction can be //! built on. //! //! ## Example //! //! ```rust //! #[macro_use] //! extern crate hamlet; //! //! use std::fmt::Write; //! //! fn main() { //! use hamlet::Token; //! let tokens = vec![ //! Token::text("Hello, "), //! Token::start_tag("small", attrs!(class="foo")), //! Token::text("world!"), //! Token::end_tag("small"), //! ]; //! //! let mut html = String::from(""); //! for token in tokens { //! write!(html, "{}", token); //! } //! //! assert_eq!(html, "Hello, <small class=\"foo\">world!</small>"); //! } //! ``` #![warn(missing_docs)] pub mod util; #[macro_use] mod macros; pub mod attr; mod escape; mod token; pub use token::Token;
//! Provides token definitions for HTML stream processing. The goal of this //! library is to provide a simple API over which higher abstraction can be //! built on. //! //! ## Example //! //! ```rust //! #[macro_use] //! extern crate hamlet; //! //! use std::fmt::Write; //! //! fn main() { //! use hamlet::Token; //! let tokens = vec![ //! Token::text("Hello, "), //! Token::start_tag("small", attrs!(class="foo")), //! Token::text("world!"), //! Token::end_tag("small"), //! ]; //! //! let mut html = String::from(""); //! for token in tokens { //! write!(html, "{}", token); //! } //! //! assert_eq!(html, "Hello, <small class=\"foo\">world!</small>"); //! } //! ``` #![warn(missing_docs)] /// Currently contains just a semi-private utility function to support the /// [`attrs!`](./macro.attrs!.html) macro. pub mod util; #[macro_use] mod macros; /// Contains structs for defining attributes on elements. pub mod attr; mod escape; mod token; pub use token::Token;
Add a trait indicating (de)serializability
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Our current on-disk metadata format uses a JSON-based structure. We // are using serde-rs, which allows us to implement serialization (to // JSON) and deserialization (from JSON) by deriving Serialize and // Deserialize traits. But, our in-memory structs are too complex for // serde to handle, and in any case it's best to not tie our real // structs to what will be saved on disk. Therefore we have *Save // structs. These contain simple, serde-friendly data types, and we // can convert to or from them when saving our current state, or // restoring state from saved metadata. // // Look for "to_save" and "setup" methods, that either return or take // the below structs as parameters. use std::collections::HashMap; use std::path::PathBuf; use devicemapper::Sectors; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BlockDevSave { pub devnode: PathBuf, pub total_size: Sectors, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StratSave { pub name: String, pub id: String, pub block_devs: HashMap<String, BlockDevSave>, }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Our current on-disk metadata format uses a JSON-based structure. We // are using serde-rs, which allows us to implement serialization (to // JSON) and deserialization (from JSON) by deriving Serialize and // Deserialize traits. But, our in-memory structs are too complex for // serde to handle, and in any case it's best to not tie our real // structs to what will be saved on disk. Therefore we have *Save // structs. These contain simple, serde-friendly data types, and we // can convert to or from them when saving our current state, or // restoring state from saved metadata. use std::collections::HashMap; use std::marker::Sized; use std::path::PathBuf; use devicemapper::Sectors; /// Implements saving and restoring from metadata. pub trait DSerializable<T> { fn to_save(&self) -> T; fn setup(T) -> Self where Self: Sized { unimplemented!() } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BlockDevSave { pub devnode: PathBuf, pub total_size: Sectors, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StratSave { pub name: String, pub id: String, pub block_devs: HashMap<String, BlockDevSave>, }
Update hint to reflect new variable binding name
// Make me compile without changing the function signature! Scroll down for hints :) fn main() { let word = String::from("green"); // Try not changing this line :) if is_a_color_word(word) { println!("That is a color word I know!"); } else { println!("That is not a color word I know."); } } fn is_a_color_word(attempt: &str) -> bool { attempt == "green" || attempt == "blue" || attempt == "red" } // Yes, it would be really easy to fix this by just changing the value bound to `guess1` to be a // string slice instead of a `String`, wouldn't it?? There is a way to add one character to line // 5, though, that will coerce the `String` into a string slice.
// Make me compile without changing the function signature! Scroll down for hints :) fn main() { let word = String::from("green"); // Try not changing this line :) if is_a_color_word(word) { println!("That is a color word I know!"); } else { println!("That is not a color word I know."); } } fn is_a_color_word(attempt: &str) -> bool { attempt == "green" || attempt == "blue" || attempt == "red" } // Yes, it would be really easy to fix this by just changing the value bound to `word` to be a // string slice instead of a `String`, wouldn't it?? There is a way to add one character to line // 5, though, that will coerce the `String` into a string slice.
Fix test that used an oversized int literal
fn f<T>(i: @int, t: T) { } fn main() { let x = bind f::<char>(@0xdeafbeef, _); }
fn f<T>(i: @uint, t: T) { } fn main() { let x = bind f::<char>(@0xdeafbeefu, _); }
Modify completes_methods_for_file_open so that racer work correctly
#![feature(test)] extern crate racer_testutils; extern crate test; use test::Bencher; use racer_testutils::*; #[bench] fn completes_hashmap(b: &mut Bencher) { let src = r" use std::collections::HashM~ "; let mut var = vec![]; b.iter(|| { var = get_all_completions(src, None); }) } #[bench] fn completes_methods_for_vec(b: &mut Bencher) { let src = r" let vec = Vec::new(); let a = vec.~ "; let mut var = vec![]; b.iter(|| { var = get_all_completions(src, None); }) } #[bench] fn completes_methods_for_file_open(b: &mut Bencher) { let src = r#" use std::io; use std::io::prelude::*; let mut f = File::open("no-file-here"): f.~ "#; let mut var = vec![]; b.iter(|| { var = get_all_completions(src, None); }) }
#![feature(test)] extern crate racer_testutils; extern crate test; use test::Bencher; use racer_testutils::*; #[bench] fn completes_hashmap(b: &mut Bencher) { let src = r" use std::collections::HashM~ "; let mut var = vec![]; b.iter(|| { var = get_all_completions(src, None); }) } #[bench] fn completes_methods_for_vec(b: &mut Bencher) { let src = r" let vec = Vec::new(); let a = vec.~ "; let mut var = vec![]; b.iter(|| { var = get_all_completions(src, None); }) } #[bench] fn completes_methods_for_file_open(b: &mut Bencher) { let src = r#" use std::io; use std::io::prelude::*; use std::fs::File; let mut f = File::open("no-file-here"): f.~ "#; let mut var = vec![]; b.iter(|| { var = get_all_completions(src, None); }) }
Remove lint for managed vectors so JSON can be parsed
#![crate_id = "rust_js"] #![crate_type = "lib"] #![comment = "Rust Javascript parsing and interpretation library"] #![license = "MIT"] #![deny(deprecated_owned_vector)] #![deny(non_uppercase_statics)] #![deny(missing_doc)] #![deny(unnecessary_parens)] #![deny(unrecognized_lint)] #![deny(unreachable_code)] #![deny(unnecessary_allocation)] #![deny(unnecessary_typecast)] #![deny(unnecessary_allocation)] #![deny(uppercase_variables)] #![deny(non_camel_case_types)] #![deny(unused_must_use)] //! A Javascript Parser / Interpreter library extern crate collections; extern crate time; extern crate serialize; extern crate rand; /// The Abstract Syntax Tree module pub mod ast; /// The lexing module pub mod lexer; /// The parsing module pub mod parser; /// The execution module pub mod exec; /// The javascript core library module pub mod js { /// Contains the Javascript value pub mod value; /// Functions pub mod function; /// Contains the Javascript object pub mod object; /// Contains the Javascript array pub mod array; /// The global console object pub mod console; /// The global math object pub mod math; /// The global JSON object pub mod json; /// Errors pub mod error; }
#![crate_id = "rust_js"] #![crate_type = "lib"] #![comment = "Rust Javascript parsing and interpretation library"] #![license = "MIT"] #![deny(non_uppercase_statics)] #![deny(missing_doc)] #![deny(unnecessary_parens)] #![deny(unrecognized_lint)] #![deny(unreachable_code)] #![deny(unnecessary_allocation)] #![deny(unnecessary_typecast)] #![deny(unnecessary_allocation)] #![deny(uppercase_variables)] #![deny(non_camel_case_types)] #![deny(unused_must_use)] //! A Javascript Parser / Interpreter library extern crate collections; extern crate time; extern crate serialize; extern crate rand; /// The Abstract Syntax Tree module pub mod ast; /// The lexing module pub mod lexer; /// The parsing module pub mod parser; /// The execution module pub mod exec; /// The javascript core library module pub mod js { /// Contains the Javascript value pub mod value; /// Functions pub mod function; /// Contains the Javascript object pub mod object; /// Contains the Javascript array pub mod array; /// The global console object pub mod console; /// The global math object pub mod math; /// The global JSON object pub mod json; /// Errors pub mod error; }
Update link to Open Sound Control 1.0 spec
//! **rosc** is an implementation of the [OSC 1.0](http://opensoundcontrol.org/spec-1_0) protocol in pure Rust. //! extern crate byteorder; extern crate regex; extern crate nom; /// Crate specific error types. mod errors; /// OSC data types, see [OSC 1.0 specification](http://opensoundcontrol.org/spec-1_0) for details. mod types; pub use crate::errors::*; pub use crate::types::*; /// Provides a decoding method for OSC packets. pub mod decoder; /// Encodes an `OscPacket` to a byte vector. pub mod encoder; /// Address checking and matching methods pub mod address;
//! **rosc** is an implementation of the [OSC 1.0](http://opensoundcontrol.org/spec-1_0) protocol in pure Rust. //! extern crate byteorder; extern crate regex; extern crate nom; /// Crate specific error types. mod errors; /// OSC data types, see [OSC 1.0 specification](https://opensoundcontrol.stanford.edu/spec-1_0.html) for details. mod types; pub use crate::errors::*; pub use crate::types::*; /// Provides a decoding method for OSC packets. pub mod decoder; /// Encodes an `OscPacket` to a byte vector. pub mod encoder; /// Address checking and matching methods pub mod address;
Put REDIS_URL between ticks in the documentation
/*! [Sidekiq](https://github.com/mperham/sidekiq) client allowing to push jobs. Using the [Sidekiq job format](https://github.com/mperham/sidekiq/wiki/Job-Format) as reference. # Default environment variables * REDIS_URL="redis://127.0.0.1/" */ #![deny(warnings)] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![crate_name = "sidekiq"] extern crate serde; extern crate serde_json; extern crate rand; extern crate r2d2; extern crate r2d2_redis; mod sidekiq; pub use serde_json::value::Value; pub use sidekiq::{Job, JobOpts, Client, ClientOpts, RedisPool, RedisPooledConnection, create_redis_pool};
/*! [Sidekiq](https://github.com/mperham/sidekiq) client allowing to push jobs. Using the [Sidekiq job format](https://github.com/mperham/sidekiq/wiki/Job-Format) as reference. # Default environment variables * `REDIS_URL`="redis://127.0.0.1/" */ #![deny(warnings)] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![crate_name = "sidekiq"] extern crate serde; extern crate serde_json; extern crate rand; extern crate r2d2; extern crate r2d2_redis; mod sidekiq; pub use serde_json::value::Value; pub use sidekiq::{Job, JobOpts, Client, ClientOpts, RedisPool, RedisPooledConnection, create_redis_pool};
Remove warnings from using unstable fs and io
use camera::Camera; use vector::Vector; use std::fs::File; use std::io::prelude::*; mod sphere; mod ray; mod colour; mod vector; mod camera; fn main() { let width = 640; let height = 480; let campos = Vector::new(1.0,1.0,1.0); let camlook = Vector::empty(); let camup = Vector::new(0.0, 1.0,0.0); let camera = Camera::new(campos, camlook,camup, 45, width, height); let mut file = File::create("img.pbm"); match file { Ok(mut file) => { file.write("P3\n".as_bytes()); file.write(format!("{} {} 255\n", camera.width, camera.height).as_bytes()); for x in 0..width { for y in 0..height { let colour = camera.trace_ray(x, y); file.write(format!("{} {} {}\n", colour.red, colour.green, colour.blue).as_bytes()); } } }, Err(str) => { println!("{:?}", str); } } }
#![feature(fs,io)] use camera::Camera; use vector::Vector; use std::fs::File; use std::io::prelude::*; mod sphere; mod ray; mod colour; mod vector; mod camera; fn main() { let width = 640; let height = 480; let campos = Vector::new(1.0,1.0,1.0); let camlook = Vector::empty(); let camup = Vector::new(0.0, 1.0,0.0); let camera = Camera::new(campos, camlook,camup, 45, width, height); let mut file = File::create("img.pbm"); match file { Ok(mut file) => { file.write("P3\n".as_bytes()); file.write(format!("{} {} 255\n", camera.width, camera.height).as_bytes()); for x in 0..width { for y in 0..height { let colour = camera.trace_ray(x, y); file.write(format!("{} {} {}\n", colour.red, colour.green, colour.blue).as_bytes()); } } }, Err(str) => { println!("{:?}", str); } } }
Use `AdditiveIterator`'s `sum()` instead of normal `fold()`.
// Implements http://rosettacode.org/wiki/Averages/Arithmetic_mean // The mean is not defined for an empty list, so we must return an Option fn mean(list: &[f64]) -> Option<f64> { match list.len() { 0 => None, n => { let sum = list.iter().fold(0 as f64, |acc, &x| acc + x); Some(sum / n as f64) } } } #[cfg(not(test))] fn main() { let input = vec!(3.0, 1.0, 4.0, 1.0, 5.0, 9.0); // This should be 3.833333 let mean = mean(input.as_slice()).unwrap(); println!("{}", mean); } #[test] fn simple_test() { let vector = vec!(1.0, 2.0, 3.0, 4.0, 5.0); assert!(mean(vector.as_slice()).unwrap() == 3.0); } #[test] fn mean_empty_list() { let empty_vec = vec!(); assert!(mean(empty_vec.as_slice()).is_none()); }
// Implements http://rosettacode.org/wiki/Averages/Arithmetic_mean use std::iter::AdditiveIterator; // The mean is not defined for an empty list, so we must return an Option fn mean(list: &[f64]) -> Option<f64> { match list.len() { 0 => None, n => { let sum = list.iter().map(|&x| x).sum(); Some(sum / n as f64) } } } #[cfg(not(test))] fn main() { let input = vec!(3.0, 1.0, 4.0, 1.0, 5.0, 9.0); // This should be 3.833333 let mean = mean(input.as_slice()).unwrap(); println!("{}", mean); } #[test] fn simple_test() { let vector = vec!(1.0, 2.0, 3.0, 4.0, 5.0); assert!(mean(vector.as_slice()).unwrap() == 3.0); } #[test] fn mean_empty_list() { let empty_vec = vec!(); assert!(mean(empty_vec.as_slice()).is_none()); }
Adjust depth when jump commands are seen
use command::Command; use vm::VM; pub struct Program { instructions : Vec<Command>, instruction_pointer: Option<usize>, is_seeking: bool, current_depth: u64, goal_depth: Option<u64>, } impl Program { pub fn new () -> Program { Program { instructions: Vec::new(), instruction_pointer: None, is_seeking: false, current_depth: 0, goal_depth: None, } } pub fn append(&mut self, instructions: &[Command]) { self.instructions.extend(instructions.iter().cloned()); if self.instruction_pointer.is_none() { self.instruction_pointer = Some(0); } } pub fn execute(&mut self, vm: &mut VM) { match self.instruction_pointer { None => {}, Some(mut index) => { while index < self.instructions.len() { let command = self.instructions[index]; vm.apply(command); index = index + 1; } self.instruction_pointer = Some(index); } } } }
use command::Command; use vm::VM; pub struct Program { instructions : Vec<Command>, instruction_pointer: Option<usize>, is_seeking: bool, current_depth: u64, goal_depth: Option<u64>, } impl Program { pub fn new () -> Program { Program { instructions: Vec::new(), instruction_pointer: None, is_seeking: false, current_depth: 0, goal_depth: None, } } pub fn append(&mut self, instructions: &[Command]) { self.instructions.extend(instructions.iter().cloned()); if self.instruction_pointer.is_none() { self.instruction_pointer = Some(0); } } pub fn execute(&mut self, vm: &mut VM) { match self.instruction_pointer { None => {}, Some(mut index) => { while index < self.instructions.len() { let command = self.instructions[index]; if command == Command::JumpForward { self.current_depth = self.current_depth + 1} if command == Command::JumpBackward { self.current_depth = self.current_depth - 1} vm.apply(command); index = index + 1; } self.instruction_pointer = Some(index); } } } }
Revert "The Digest buffer should public (fields are private by default now)"
#![macro_escape] macro_rules! hash_module (($hash_name:ident, $hashbytes:expr, $blockbytes:expr) => ( #[link(name = "sodium")] extern { fn $hash_name(h: *mut u8, m: *u8, mlen: c_ulonglong) -> c_int; } pub static HASHBYTES: uint = $hashbytes; pub static BLOCKBYTES: uint = $blockbytes; /** * Digest-structure */ pub struct Digest(pub [u8, ..HASHBYTES]); /** * `hash` hashes a message `m`. It returns a hash `h`. */ pub fn hash(m: &[u8]) -> Digest { unsafe { let mut h = [0, ..HASHBYTES]; $hash_name(h.as_mut_ptr(), m.as_ptr(), m.len() as c_ulonglong); Digest(h) } } ))
#![macro_escape] macro_rules! hash_module (($hash_name:ident, $hashbytes:expr, $blockbytes:expr) => ( #[link(name = "sodium")] extern { fn $hash_name(h: *mut u8, m: *u8, mlen: c_ulonglong) -> c_int; } pub static HASHBYTES: uint = $hashbytes; pub static BLOCKBYTES: uint = $blockbytes; /** * Digest-structure */ pub struct Digest([u8, ..HASHBYTES]); /** * `hash` hashes a message `m`. It returns a hash `h`. */ pub fn hash(m: &[u8]) -> Digest { unsafe { let mut h = [0, ..HASHBYTES]; $hash_name(h.as_mut_ptr(), m.as_ptr(), m.len() as c_ulonglong); Digest(h) } } ))
Exit if quit or exit are entered on the REPL
use std::io; use std::io::prelude::*; use job::jobs; use agent::client; pub fn start() { let mut stdout = io::stdout(); loop { write!(&mut stdout, "builr> "); stdout.flush(); let input = &mut String::new(); match io::stdin().read_line(input) { Ok(x)=> { let input = input.replace("\n", ""); if input.len() > 0 { println!("{:?} {:?}", input, x); if "jobs" == input { jobs::list(); } else if "ping" == input { client::ping(4); } } }, Err(e) => { panic!("{}", e); } } } }
use std::io; use std::io::prelude::*; use std::process; use job::jobs; use agent::client; pub fn start() { let mut stdout = io::stdout(); loop { write!(&mut stdout, "builr> "); stdout.flush(); let input = &mut String::new(); match io::stdin().read_line(input) { Ok(x)=> { let input = input.replace("\n", ""); if input.len() > 0 { println!("{:?} {:?}", input, x); if "jobs" == input { jobs::list(); } else if "ping" == input { client::ping(4); } else if "exit" == input || "quit" == input { process::exit(0); } } }, Err(e) => { panic!("{}", e); } } } }
Make a common module of exit statuses
extern crate exa; use exa::Exa; use std::env::args_os; use std::io::{stdout, stderr, Write, ErrorKind}; use std::process::exit; fn main() { let args = args_os().skip(1); match Exa::new(args, &mut stdout()) { Ok(mut exa) => { match exa.run() { Ok(exit_status) => exit(exit_status), Err(e) => { match e.kind() { ErrorKind::BrokenPipe => exit(0), _ => { writeln!(stderr(), "{}", e).unwrap(); exit(1); }, }; } }; }, Err(ref e) if e.is_error() => { writeln!(stderr(), "{}", e).unwrap(); exit(3); }, Err(ref e) => { writeln!(stdout(), "{}", e).unwrap(); exit(0); }, }; }
extern crate exa; use exa::Exa; use std::env::args_os; use std::io::{stdout, stderr, Write, ErrorKind}; use std::process::exit; fn main() { let args = args_os().skip(1); match Exa::new(args, &mut stdout()) { Ok(mut exa) => { match exa.run() { Ok(exit_status) => exit(exit_status), Err(e) => { match e.kind() { ErrorKind::BrokenPipe => exit(exits::SUCCESS), _ => { writeln!(stderr(), "{}", e).unwrap(); exit(exits::RUNTIME_ERROR); }, }; } }; }, Err(ref e) if e.is_error() => { writeln!(stderr(), "{}", e).unwrap(); exit(exits::OPTIONS_ERROR); }, Err(ref e) => { writeln!(stdout(), "{}", e).unwrap(); exit(exits::SUCCESS); }, }; } extern crate libc; #[allow(trivial_numeric_casts)] mod exits { use libc::{self, c_int}; pub const SUCCESS: c_int = libc::EXIT_SUCCESS; pub const RUNTIME_ERROR: c_int = libc::EXIT_FAILURE; pub const OPTIONS_ERROR: c_int = 3 as c_int; }
Remove magic constant from buffer copying code.
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. use std::io::{Read, Write, Result}; pub fn copy_until<R, W, P>(reader: &mut R, writer: &mut W, mut pred: P) -> Result<()> where R: Read, W: Write, P: FnMut(&R, &W) -> bool, { // TODO: Move the magic number to a constant. let mut buf = [0; 1024]; loop { use std::io::ErrorKind::*; let len = match reader.read(&mut buf[..]) { Ok(0) => break, Ok(len) => len, Err(ref error) if error.kind() == Interrupted => continue, Err(error) => return Err(error), }; writer.write_all(&buf[..len])?; if pred(reader, writer) { break; } } Ok(()) } // TODO: Write tests.
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. use std::io::{Read, Write, Result}; // The same as in the Rust's standard library. const DEFAULT_BUF_SIZE: usize = 8 * 1024; pub fn copy_until<R, W, P>(reader: &mut R, writer: &mut W, mut pred: P) -> Result<()> where R: Read, W: Write, P: FnMut(&R, &W) -> bool, { let mut buf = [0; DEFAULT_BUF_SIZE]; loop { use std::io::ErrorKind::*; let len = match reader.read(&mut buf[..]) { Ok(0) => break, Ok(len) => len, Err(ref error) if error.kind() == Interrupted => continue, Err(error) => return Err(error), }; writer.write_all(&buf[..len])?; if pred(reader, writer) { break; } } Ok(()) } // TODO: Write tests.
Add ignore-asmjs to new test
// build-pass // compile-flags: -g pub struct Dst { pub a: (), pub b: (), pub data: [u8], } pub unsafe fn borrow(bytes: &[u8]) -> &Dst { let dst: &Dst = std::mem::transmute((bytes.as_ptr(), bytes.len())); dst } fn main() {}
// build-pass // ignore-asmjs wasm2js does not support source maps yet // compile-flags: -g pub struct Dst { pub a: (), pub b: (), pub data: [u8], } pub unsafe fn borrow(bytes: &[u8]) -> &Dst { let dst: &Dst = std::mem::transmute((bytes.as_ptr(), bytes.len())); dst } fn main() {}
Extend url in titles test
#![crate_name = "foo"] // @has foo/fn.foo.html // !@has - '//a[@href="http://a.a"]' // @has - '//a[@href="#implementing-stuff-somewhere"]' 'Implementing stuff somewhere' /// fooo /// /// # Implementing [stuff](http://a.a) somewhere /// /// hello pub fn foo() {}
#![crate_name = "foo"] // @has foo/fn.foo.html // !@has - '//a[@href="http://a.a"]' // @has - '//a[@href="#implementing-stuff-somewhere"]' 'Implementing stuff somewhere' // @has - '//a[@href="#another-one-urg"]' 'Another one urg' /// fooo /// /// # Implementing [stuff](http://a.a) somewhere /// /// hello /// /// # Another [one][two] urg /// /// [two]: http://a.a pub fn foo() {}
Convert Rust string type to C char type with unstable feature.... :<
extern crate ruroonga; use ruroonga::*; use std::ffi::CStr; use std::str; fn main() { unsafe { let ctx = groonga_init(); println!("Hello in Ruroonga with Groonga: {}", get_groonga_version()); let _ = groonga_fin(ctx); } }
#![feature(libc)] #![feature(collections)] #![feature(convert)] extern crate ruroonga; extern crate libc; use ruroonga::*; use std::ffi::CStr; use std::ffi::CString; use std::str; use std::string::String; fn main() { unsafe { let ctx = groonga_init(); let mut string = "test.db".to_string(); let bytes = string.into_bytes(); let mut x : Vec<libc::c_char> = bytes.map_in_place(|w| w as libc::c_char);; let slice = x.as_mut_slice(); let dbpath = slice.as_mut_ptr(); let db_ctx = grn_db_create(ctx, dbpath, None); println!("Hello in Ruroonga with Groonga: {}", get_groonga_version()); let _ = groonga_fin(ctx); } }
Add `__error` to freebsd shims
use rustc_middle::mir; use rustc_span::Symbol; use rustc_target::spec::abi::Abi; use crate::*; use shims::foreign_items::EmulateByNameResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { fn emulate_foreign_item_by_name( &mut self, link_name: Symbol, abi: Abi, args: &[OpTy<'tcx, Tag>], dest: &PlaceTy<'tcx, Tag>, _ret: mir::BasicBlock, ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> { let this = self.eval_context_mut(); match link_name.as_str() { // Linux's `pthread_getattr_np` equivalent "pthread_attr_get_np" if this.frame_in_std() => { let [_thread, _attr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; this.write_null(dest)?; } _ => return Ok(EmulateByNameResult::NotSupported), } Ok(EmulateByNameResult::NeedsJumping) } }
use rustc_middle::mir; use rustc_span::Symbol; use rustc_target::spec::abi::Abi; use crate::*; use shims::foreign_items::EmulateByNameResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { fn emulate_foreign_item_by_name( &mut self, link_name: Symbol, abi: Abi, args: &[OpTy<'tcx, Tag>], dest: &PlaceTy<'tcx, Tag>, _ret: mir::BasicBlock, ) -> InterpResult<'tcx, EmulateByNameResult<'mir, 'tcx>> { let this = self.eval_context_mut(); match link_name.as_str() { // Linux's `pthread_getattr_np` equivalent "pthread_attr_get_np" if this.frame_in_std() => { let [_thread, _attr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; this.write_null(dest)?; } // errno "__error" => { let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let errno_place = this.last_error_place()?; this.write_scalar(errno_place.to_ref(this).to_scalar()?, dest)?; } _ => return Ok(EmulateByNameResult::NotSupported), } Ok(EmulateByNameResult::NeedsJumping) } }
Implement "Drop" trait for CodeCache
extern crate libc; use std::ops::Index; use std::{ptr, mem}; use chip8::MEMORY_SIZE; use chip8::codeblock::CodeBlock; pub struct CodeCache { code_blocks: [*mut CodeBlock; MEMORY_SIZE] } impl CodeCache { pub fn new() -> CodeCache { CodeCache { code_blocks: [ptr::null_mut(); MEMORY_SIZE] } } pub fn contains_block(&self, address: u16) -> bool { !self.code_blocks[address as usize].is_null() } pub fn insert(&mut self, address: u16, code_block: CodeBlock) { unsafe { let new_ptr = libc::malloc(mem::size_of::<CodeBlock>()) as *mut CodeBlock; ptr::write(new_ptr, code_block); self.code_blocks[address as usize] = new_ptr; } } } impl Index<u16> for CodeCache { type Output = CodeBlock; fn index(&self, address: u16) -> &CodeBlock { unsafe { self.code_blocks[address as usize].as_ref().unwrap() } } }
extern crate libc; use std::ops::Index; use std::{ptr, mem}; use chip8::MEMORY_SIZE; use chip8::codeblock::CodeBlock; pub struct CodeCache { code_blocks: [*mut CodeBlock; MEMORY_SIZE] } impl CodeCache { pub fn new() -> CodeCache { CodeCache { code_blocks: [ptr::null_mut(); MEMORY_SIZE] } } pub fn contains_block(&self, address: u16) -> bool { !self.code_blocks[address as usize].is_null() } pub fn insert(&mut self, address: u16, code_block: CodeBlock) { unsafe { let new_ptr = libc::malloc(mem::size_of::<CodeBlock>()) as *mut CodeBlock; ptr::write(new_ptr, code_block); self.code_blocks[address as usize] = new_ptr; } } } impl Index<u16> for CodeCache { type Output = CodeBlock; fn index(&self, address: u16) -> &CodeBlock { unsafe { self.code_blocks[address as usize].as_ref().unwrap() } } } impl Drop for CodeCache { fn drop(&mut self) { for iter in self.code_blocks.iter() { if !(*iter).is_null() { unsafe { ptr::drop_in_place(*iter); libc::free(*iter as *mut libc::c_void); } } } } }
Add ui test of mutable slice return from reference arguments
#[cxx::bridge] mod ffi { extern "Rust" { type Mut<'a>; } unsafe extern "C++" { type Thing; fn f(t: &Thing) -> Pin<&mut CxxString>; unsafe fn g(t: &Thing) -> Pin<&mut CxxString>; fn h(t: Box<Mut>) -> Pin<&mut CxxString>; fn i<'a>(t: Box<Mut<'a>>) -> Pin<&'a mut CxxString>; } } fn main() {}
#[cxx::bridge] mod ffi { extern "Rust" { type Mut<'a>; } unsafe extern "C++" { type Thing; fn f(t: &Thing) -> Pin<&mut CxxString>; unsafe fn g(t: &Thing) -> Pin<&mut CxxString>; fn h(t: Box<Mut>) -> Pin<&mut CxxString>; fn i<'a>(t: Box<Mut<'a>>) -> Pin<&'a mut CxxString>; fn j(t: &Thing) -> &mut [u8]; } } fn main() {}
Disable aarch64 outline atomics with musl for now.
use crate::spec::{Target, TargetOptions}; pub fn target() -> Target { let mut base = super::linux_musl_base::opts(); base.max_atomic_width = Some(128); Target { llvm_target: "aarch64-unknown-linux-musl".to_string(), pointer_width: 64, data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), options: TargetOptions { features: "+outline-atomics".to_string(), mcount: "\u{1}_mcount".to_string(), ..base }, } }
use crate::spec::{Target, TargetOptions}; pub fn target() -> Target { let mut base = super::linux_musl_base::opts(); base.max_atomic_width = Some(128); Target { llvm_target: "aarch64-unknown-linux-musl".to_string(), pointer_width: 64, data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), options: TargetOptions { mcount: "\u{1}_mcount".to_string(), ..base }, } }
Add OS checking using cfg
use std::rand::random; mod guess { pub fn guessed_correctly(guess: uint, machine: uint) -> bool { guess == machine } } fn main() { let random_value = random::<uint>() % 10u; let mut guess = 0u; guess += 1; println!("{}", random_value); println!("{}", guess::guessed_correctly(guess, random_value)); }
use std::io; use std::rand::random; mod guess { pub fn guessed_correctly(guess: uint, machine: uint) -> bool { guess == machine } } #[cfg(not(target_os = "linux"))] fn test_os() { println!("You are not running Linux!") } fn main() { test_os(); let random_value = random::<uint>() % 10u; let mut guess = 0u; for line in io::stdin().lines() { // guess = line.unwrap().to_int(); println!("{}", line.unwrap()); } println!("{}", random_value); println!("{}", guess); println!("{}", guess::guessed_correctly(guess, random_value)); }
Add ..= const { .. } missing tests and sort them properly
// build-pass #![allow(incomplete_features)] #![feature(inline_const, half_open_range_patterns, exclusive_range_pattern)] fn main() { const N: u32 = 10; let x: u32 = 3; match x { const { N - 1 } ..= 10 => {}, _ => {}, } match x { const { N - 1 } ..= const { N + 1 } => {}, _ => {}, } match x { 1 ..= const { N + 1 } => {}, _ => {}, } match x { .. const { N + 1 } => {}, _ => {}, } match x { const { N - 1 } .. => {}, _ => {}, } }
// build-pass #![allow(incomplete_features)] #![feature(inline_const, half_open_range_patterns, exclusive_range_pattern)] fn main() { const N: u32 = 10; let x: u32 = 3; match x { 1 ..= const { N + 1 } => {}, _ => {}, } match x { const { N - 1 } ..= 10 => {}, _ => {}, } match x { const { N - 1 } ..= const { N + 1 } => {}, _ => {}, } match x { .. const { N + 1 } => {}, _ => {}, } match x { const { N - 1 } .. => {}, _ => {}, } match x { ..= const { N + 1 } => {}, _ => {} } }
Add a description to the library
extern crate arguments; extern crate hiredis; extern crate mcpat; extern crate sql; extern crate sqlite; #[macro_use] extern crate log; /// Raise an error. #[macro_export] macro_rules! raise( ($message:expr) => (return Err($crate::Error::new($message))); ); /// Unwrap a result or raise an error. #[macro_export] macro_rules! ok( ($result:expr) => ( match $result { Ok(result) => result, Err(error) => raise!(error), } ); ); mod result; mod system; pub mod database; pub mod server; pub use result::{Error, Result}; pub use system::System;
//! Recording of workload patterns. extern crate arguments; extern crate hiredis; extern crate mcpat; extern crate sql; extern crate sqlite; #[macro_use] extern crate log; /// Raise an error. #[macro_export] macro_rules! raise( ($message:expr) => (return Err($crate::Error::new($message))); ); /// Unwrap a result or raise an error. #[macro_export] macro_rules! ok( ($result:expr) => ( match $result { Ok(result) => result, Err(error) => raise!(error), } ); ); mod result; mod system; pub mod database; pub mod server; pub use result::{Error, Result}; pub use system::System;
Add helper to get the branch which must be checked out before any action takes place
use toml::Value; use vcs::git::action::StoreAction; pub fn commit_interactive(config: &Value) -> bool { unimplemented!() } pub fn commit_message(config: &Value, action: StoreAction) -> Option<String> { if commit_interactive(config) { unimplemented!() } else { unimplemented!() } } pub fn abort_on_repo_init_err(cfg: Option<&Value>) -> bool { cfg.map(|cfg| { match cfg.lookup("abort_on_repo_init_failure") { Some(&Value::Boolean(b)) => b, Some(_) => { warn!("Configuration error, 'abort_on_repo_init_failure' must be a Boolean (true|false)."); warn!("Assuming 'true' now."); true }, None => { debug!("No key `abort_on_repo_init_failure' - Assuming 'true'"); true }, } }) .unwrap_or(false) }
use toml::Value; use libimagerror::into::IntoError; use vcs::git::error::GitHookErrorKind as GHEK; use vcs::git::error::MapErrInto; use vcs::git::result::Result; use vcs::git::action::StoreAction; pub fn commit_interactive(config: &Value) -> bool { unimplemented!() } pub fn commit_message(config: &Value, action: StoreAction) -> Option<String> { if commit_interactive(config) { unimplemented!() } else { unimplemented!() } } pub fn abort_on_repo_init_err(cfg: Option<&Value>) -> bool { cfg.map(|cfg| { match cfg.lookup("abort_on_repo_init_failure") { Some(&Value::Boolean(b)) => b, Some(_) => { warn!("Configuration error, 'abort_on_repo_init_failure' must be a Boolean (true|false)."); warn!("Assuming 'true' now."); true }, None => { debug!("No key `abort_on_repo_init_failure' - Assuming 'true'"); true }, } }) .unwrap_or(false) } pub fn ensure_branch(cfg: Option<&Value>) -> Result<Option<String>> { match cfg { Some(cfg) => { match cfg.lookup("ensure_branch") { Some(&Value::String(ref s)) => Ok(Some(s.clone())), Some(_) => { warn!("Configuration error, 'ensure_branch' must be a String."); Err(GHEK::ConfigTypeError.into_error()) .map_err_into(GHEK::ConfigTypeError) }, None => { debug!("No key `ensure_branch'"); Ok(None) }, } }, None => Ok(None), } }
Update unsized error msg pattern again
// error-pattern:the size for value values of type `str` cannot be known at compilation time #[macro_use] extern crate lazy_static_compiletest as lazy_static; lazy_static! { pub static ref FOO: str = panic!(); } fn main() { }
// error-pattern:the size for values of type `str` cannot be known at compilation time #[macro_use] extern crate lazy_static_compiletest as lazy_static; lazy_static! { pub static ref FOO: str = panic!(); } fn main() { }
Fix link to documentation of PcapWriter
#![allow(clippy::unreadable_literal)] //! This crate contains parsers and readers for Pcap and Pcapng files. //! It also contains a writer for Pcap files. //! //! For Pcap files see //! [PcapReader](struct.PcapReader.html), [PcapParser](struct.PcapParser.html) and [PcapWriter](struct.PcapParser.html). //! //! For PcapNg files see //! [PcapNgReader](struct.PcapNgReader.html) and [PcapNgParser](struct.PcapNgParser.html). pub(crate) mod common; pub use common::*; pub(crate) mod errors; pub use errors::*; pub mod pcap; pub use pcap::{PcapReader, PcapParser, PcapWriter}; pub mod pcapng; pub use pcapng::{PcapNgReader, PcapNgParser}; pub(crate) mod peek_reader;
#![allow(clippy::unreadable_literal)] //! This crate contains parsers and readers for Pcap and Pcapng files. //! It also contains a writer for Pcap files. //! //! For Pcap files see //! [PcapReader](struct.PcapReader.html), [PcapParser](struct.PcapParser.html) and [PcapWriter](struct.PcapWriter.html). //! //! For PcapNg files see //! [PcapNgReader](struct.PcapNgReader.html) and [PcapNgParser](struct.PcapNgParser.html). pub(crate) mod common; pub use common::*; pub(crate) mod errors; pub use errors::*; pub mod pcap; pub use pcap::{PcapReader, PcapParser, PcapWriter}; pub mod pcapng; pub use pcapng::{PcapNgReader, PcapNgParser}; pub(crate) mod peek_reader;
Add elapsed time to binary
extern crate sonos_discovery; use sonos_discovery::Discover; fn main() { let discovery = Discover::new().unwrap(); let devices = discovery.start(None, Some(3)).unwrap(); for device in devices { println!("{:?}", device) } }
extern crate sonos_discovery; use sonos_discovery::Discover; use std::time::Instant; fn main() { let start_time = Instant::now(); let discovery = Discover::new().unwrap(); let ips = discovery.start(None, Some(3)).unwrap(); for ip in ips { println!("{:?}", ip) } println!("\nTime: {:?}", start_time.elapsed()) }
Update test a bit more to hopefully work on Linux/Win.
#![cfg_attr(feature = "nightly", feature(lang_items, core_intrinsics, panic_implementation))] #![cfg_attr(feature = "nightly", no_std)] #![cfg_attr(feature = "nightly", no_main)] // Pull in the system libc library for what crt0.o likely requires. extern crate libc; extern crate raw_cpuid; #[cfg(feature = "nightly")] use core::panic::PanicInfo; #[cfg(feature = "nightly")] #[no_mangle] pub extern "C" fn main(_argc: i32, _argv: *const *const u8) -> i32 { let _c = raw_cpuid::CpuId::new(); 0 } #[cfg(not(feature = "nightly"))] fn main() { let _c = raw_cpuid::CpuId::new(); } #[cfg_attr(feature = "nightly", lang = "eh_personality")] #[no_mangle] pub extern "C" fn rust_eh_personality() {} #[cfg_attr(feature = "nightly", lang = "eh_unwind_resume")] #[no_mangle] pub extern "C" fn rust_eh_unwind_resume() {} #[cfg(feature = "nightly")] #[cfg_attr(feature = "nightly", panic_implementation)] fn panic_impl(_info: &PanicInfo) -> ! { loop {} }
#![cfg_attr(feature = "nightly", feature(lang_items, core_intrinsics, panic_implementation))] #![cfg_attr(feature = "nightly", no_std)] #![cfg_attr(feature = "nightly", no_main)] // Pull in the system libc library for what crt0.o likely requires. extern crate libc; extern crate raw_cpuid; #[cfg(feature = "nightly")] use core::panic::PanicInfo; #[cfg(feature = "nightly")] #[no_mangle] pub extern "C" fn main(_argc: i32, _argv: *const *const u8) -> i32 { let _c = raw_cpuid::CpuId::new(); 0 } #[cfg(not(feature = "nightly"))] fn main() { let _c = raw_cpuid::CpuId::new(); } #[cfg(feature = "nightly")] #[cfg_attr(feature = "nightly", lang = "eh_personality")] #[no_mangle] pub extern "C" fn rust_eh_personality() {} #[cfg(feature = "nightly")] #[cfg_attr(feature = "nightly", lang = "eh_unwind_resume")] #[no_mangle] pub extern "C" fn rust_eh_unwind_resume() {} #[cfg(feature = "nightly")] #[cfg_attr(feature = "nightly", panic_implementation)] fn panic_impl(_info: &PanicInfo) -> ! { loop {} }
Define a method on struct that uses generics
fn largest<T>(list: &[T]) -> T { let mut largest = list[0]; for &item in list.iter() { if item > largest { largest = item; } } largest } struct Point<T> { x: T, y: T, } fn main() { let numbers = vec![1, 3, 2, 5, 0]; let result = largest(&numbers); println!("The largest number is {}", result); }
fn largest<T>(list: &[T]) -> T { let mut largest = list[0]; for &item in list.iter() { if item > largest { largest = item; } } largest } struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn x(&self) -> &T { &self.x } } fn main() { let numbers = vec![1, 3, 2, 5, 0]; let result = largest(&numbers); println!("The largest number is {}", result); }
Update tests for Rust 2018
extern crate crowbook; use crowbook::Book; use std::io; #[test] fn test_book() { let mut book = Book::new(); book.load_file(&format!("{}/{}", env!("CARGO_MANIFEST_DIR"), "tests/test.book")) .unwrap(); book.render_format_to("html", &mut io::sink()).unwrap(); book.render_format_to("tex", &mut io::sink()).unwrap(); } #[test] fn book_example() { let mut book = Book::new(); book.load_file(&format!("{}/{}", env!("CARGO_MANIFEST_DIR"), "guide.book")) .unwrap(); book.render_format_to("html", &mut io::sink()).unwrap(); book.render_format_to("tex", &mut io::sink()).unwrap(); }
use crowbook::Book; use std::io; #[test] fn test_book() { let mut book = Book::new(); book.load_file(&format!("{}/{}", env!("CARGO_MANIFEST_DIR"), "tests/test.book")) .unwrap(); book.render_format_to("html", &mut io::sink()).unwrap(); book.render_format_to("tex", &mut io::sink()).unwrap(); } #[test] fn book_example() { let mut book = Book::new(); book.load_file(&format!("{}/{}", env!("CARGO_MANIFEST_DIR"), "guide.book")) .unwrap(); book.render_format_to("html", &mut io::sink()).unwrap(); book.render_format_to("tex", &mut io::sink()).unwrap(); }
Mark deduplicated errors as expected in gate test
#![deny(unsafe_op_in_unsafe_fn)] //~^ ERROR the `unsafe_op_in_unsafe_fn` lint is unstable fn main() {}
#![deny(unsafe_op_in_unsafe_fn)] //~^ ERROR the `unsafe_op_in_unsafe_fn` lint is unstable //~| ERROR the `unsafe_op_in_unsafe_fn` lint is unstable //~| ERROR the `unsafe_op_in_unsafe_fn` lint is unstable fn main() {}
Add some tests to make sure we can parse the syntax JSON file
use serde_json::*; use super::super::lex::*; /// /// Creates a lexing tool for the scripting language /// pub fn create_lex_script_tool() -> StringLexingTool { // Parse the lexer let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json")).unwrap(); // The name isn't used here, but define it anyway let lex_defn = LexToolInput { new_tool_name: String::from("lex-script"), symbols: script_json }; // Create the lexing tool with this definition StringLexingTool::from_lex_tool_input(&lex_defn) }
use serde_json::*; use super::super::lex::*; /// /// Creates a lexing tool for the scripting language /// pub fn create_lex_script_tool() -> StringLexingTool { // Parse the lexer let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json")).unwrap(); // The name isn't used here, but define it anyway let lex_defn = LexToolInput { new_tool_name: String::from("lex-script"), symbols: script_json }; // Create the lexing tool with this definition StringLexingTool::from_lex_tool_input(&lex_defn) } #[cfg(test)] mod test { use std::error::Error; use super::*; #[test] fn can_parse_syntax_json() { let script_json = from_str::<Value>(include_str!("syntax_lexer.json")); if script_json.is_err() { println!("{:?}", script_json); println!("{:?}", script_json.unwrap_err().description()); assert!(false); } } #[test] fn json_can_be_deserialized() { let script_json = from_str::<Vec<LexToolSymbol>>(include_str!("syntax_lexer.json")); if script_json.is_err() { println!("{:?}", script_json); } script_json.unwrap(); } #[test] fn can_create_tool() { let _tool = create_lex_script_tool(); } }
Add none-group statement parsing test
#[macro_use] mod macros; use syn::Stmt; #[test] fn test_raw_operator() { let stmt = syn::parse_str::<Stmt>("let _ = &raw const x;").unwrap(); snapshot!(stmt, @r###" Local(Local { pat: Pat::Wild, init: Some(Verbatim(`& raw const x`)), }) "###); } #[test] fn test_raw_variable() { let stmt = syn::parse_str::<Stmt>("let _ = &raw;").unwrap(); snapshot!(stmt, @r###" Local(Local { pat: Pat::Wild, init: Some(Expr::Reference { expr: Expr::Path { path: Path { segments: [ PathSegment { ident: "raw", arguments: None, }, ], }, }, }), }) "###); } #[test] fn test_raw_invalid() { assert!(syn::parse_str::<Stmt>("let _ = &raw x;").is_err()); }
#[macro_use] mod macros; use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; use std::iter::FromIterator; use syn::Stmt; #[test] fn test_raw_operator() { let stmt = syn::parse_str::<Stmt>("let _ = &raw const x;").unwrap(); snapshot!(stmt, @r###" Local(Local { pat: Pat::Wild, init: Some(Verbatim(`& raw const x`)), }) "###); } #[test] fn test_raw_variable() { let stmt = syn::parse_str::<Stmt>("let _ = &raw;").unwrap(); snapshot!(stmt, @r###" Local(Local { pat: Pat::Wild, init: Some(Expr::Reference { expr: Expr::Path { path: Path { segments: [ PathSegment { ident: "raw", arguments: None, }, ], }, }, }), }) "###); } #[test] fn test_raw_invalid() { assert!(syn::parse_str::<Stmt>("let _ = &raw x;").is_err()); } #[test] fn test_none_group() { // <Ø async fn f() {} Ø> let tokens = TokenStream::from_iter(vec![TokenTree::Group(Group::new( Delimiter::None, TokenStream::from_iter(vec![ TokenTree::Ident(Ident::new("async", Span::call_site())), TokenTree::Ident(Ident::new("fn", Span::call_site())), TokenTree::Ident(Ident::new("f", Span::call_site())), TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::new())), TokenTree::Group(Group::new(Delimiter::Brace, TokenStream::new())), ]), ))]); snapshot!(tokens as Stmt, @r###" Item(Item::Fn { vis: Inherited, sig: Signature { asyncness: Some, ident: "f", generics: Generics, output: Default, }, block: Block, }) "###); }
Add test for Array of char
extern crate test; extern crate ndarray; use ndarray::Array; #[bench] fn time_matmul(b: &mut test::Bencher) { b.iter(|| { let mut a: Array<uint, (uint, uint)> = Array::zeros((2u, 3u)); for (i, elt) in a.iter_mut().enumerate() { *elt = i; } let mut b: Array<uint, (uint, uint)> = Array::zeros((3u, 4u)); for (i, elt) in b.iter_mut().enumerate() { *elt = i; } let c = a.mat_mul(&b); unsafe { let result = Array::from_vec_dim((2u, 4u), vec![20u, 23, 26, 29, 56, 68, 80, 92]); assert!(c == result); } }) }
extern crate test; extern crate ndarray; use ndarray::Array; #[test] fn char_array() { // test compilation & basics of non-numerical array let cc = Array::from_iter("alphabet".chars()).reshape((4u, 2u)); assert!(cc.at_sub(1, 0) == Array::from_iter("apae".chars())); } #[bench] fn time_matmul(b: &mut test::Bencher) { b.iter(|| { let mut a: Array<uint, (uint, uint)> = Array::zeros((2u, 3u)); for (i, elt) in a.iter_mut().enumerate() { *elt = i; } let mut b: Array<uint, (uint, uint)> = Array::zeros((3u, 4u)); for (i, elt) in b.iter_mut().enumerate() { *elt = i; } let c = a.mat_mul(&b); unsafe { let result = Array::from_vec_dim((2u, 4u), vec![20u, 23, 26, 29, 56, 68, 80, 92]); assert!(c == result); } }) }
Move construction of names to local vars first
///! ///! Standard plugin is of the type of view plugins and backend plugins ///! which follows the same structure in the shared libs ///! use dynamic_reload::Lib; use libc::{c_char, c_void}; use std::rc::Rc; use std::mem::transmute; use std::ffi::CStr; #[repr(C)] pub struct CBasePlugin { pub name: *const c_char, } pub struct Plugin { pub lib: Rc<Lib>, pub name: String, pub type_name: String, pub plugin_funcs: *mut CBasePlugin, } impl Plugin { pub fn new(lib: &Rc<Lib>, plugin_type: *const c_char, plugin: *mut c_void) -> Plugin { unsafe { let plugin_funcs: *mut CBasePlugin = transmute(plugin); Plugin { lib: lib.clone(), type_name: CStr::from_ptr(plugin_type).to_string_lossy().into_owned(), name: CStr::from_ptr((*plugin_funcs).name).to_string_lossy().into_owned(), plugin_funcs: plugin_funcs, } } } } #[cfg(test)] mod tests { }
///! ///! Standard plugin is of the type of view plugins and backend plugins ///! which follows the same structure in the shared libs ///! use dynamic_reload::Lib; use libc::{c_char, c_void}; use std::rc::Rc; use std::mem::transmute; use std::ffi::CStr; #[repr(C)] pub struct CBasePlugin { pub name: *const c_char, } pub struct Plugin { pub lib: Rc<Lib>, pub name: String, pub type_name: String, pub plugin_funcs: *mut CBasePlugin, } impl Plugin { pub fn new(lib: &Rc<Lib>, plugin_type: *const c_char, plugin: *mut c_void) -> Plugin { unsafe { let plugin_funcs: *mut CBasePlugin = transmute(plugin); let type_name = CStr::from_ptr(plugin_type); let name = CStr::from_ptr((*plugin_funcs).name); Plugin { lib: lib.clone(), type_name: type_name.to_string_lossy().into_owned(), name: name.to_string_lossy().into_owned(), plugin_funcs: plugin_funcs, } } } } #[cfg(test)] mod tests { }
Enable show karma module functionality
extern crate rustix; use std::io::Read; use std::fs::File; use rustix::bot; use rustix::client::MatrixClient; use rustix::services::echo::*; use rustix::services::self_filter::*; use rustix::services::upvote::*; fn main() { let mut m = MatrixClient::new("https://cclub.cs.wmich.edu/"); let mut password = String::new(); let mut f = File::open("auth").expect("auth file not found"); f.read_to_string(&mut password).expect("something went wrong reading file"); m.login("rustix", password.trim()).expect("login failed!"); m.set_display_name("rustix"); let mut b = bot::Bot::new(&mut m); let sf = b.register_service("self_filter", None, Box::new(SelfFilter::new())); b.register_service("echo", sf, Box::new(Echo::new())); b.register_service("upvote_tracker", sf, Box::new(UpvoteTracker::new())); b.run(); }
extern crate rustix; use std::io::Read; use std::fs::File; use rustix::bot; use rustix::client::MatrixClient; use rustix::services::echo::*; use rustix::services::self_filter::*; use rustix::services::upvote::*; fn main() { let mut m = MatrixClient::new("https://cclub.cs.wmich.edu/"); let mut password = String::new(); let mut f = File::open("auth").expect("auth file not found"); f.read_to_string(&mut password).expect("something went wrong reading file"); m.login("rustix", password.trim()).expect("login failed!"); m.set_display_name("rustix"); let mut b = bot::Bot::new(&mut m); let sf = b.register_service("self_filter", None, Box::new(SelfFilter::new())); b.register_service("echo", sf, Box::new(Echo::new())); b.register_service("upvote_tracker", sf, Box::new(UpvoteTracker::new())); b.register_service("show_karma", sf, Box::new(show_karma::ShowKarma::new())); b.run(); }
Replace contents with big text box
extern crate orbtk; #[cfg(target_os = "redox")] #[no_mangle] pub fn main() { orbtk::example(); } #[cfg(not(target_os = "redox"))] fn main() { orbtk::example(); }
extern crate orbtk; use orbtk::*; fn real_main(){ let mut window = Window::new(Rect::new(100, 100, 420, 420), "Editor"); TextBox::new() .position(0, 0) .size(420, 420) .place(&mut window); window.exec(); } #[cfg(target_os = "redox")] #[no_mangle] pub fn main() { real_main(); } #[cfg(not(target_os = "redox"))] fn main() { real_main(); }
Mark unused_qualifications as a warning
#![crate_type = "lib"] #![deny(missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications)] #![warn(missing_docs)] //! This is a base library for dealing with DICOM information and communication. //! //! Sorry, no example yet! //! #[macro_use] extern crate lazy_static; extern crate byteorder; extern crate encoding; #[macro_use] extern crate quick_error; pub mod attribute; pub mod error; pub mod parser; pub mod transfer_syntax; pub mod data_element; pub mod meta; mod util;
#![crate_type = "lib"] #![deny(missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces)] #![warn(missing_docs, unused_qualifications)] //! This is a base library for dealing with DICOM information and communication. //! //! Sorry, no example yet! //! #[macro_use] extern crate lazy_static; extern crate byteorder; extern crate encoding; #[macro_use] extern crate quick_error; pub mod attribute; pub mod error; pub mod parser; pub mod transfer_syntax; pub mod data_element; pub mod meta; mod util;
Allow reading the input from stdin
#[macro_use] extern crate clap; extern crate regex; extern crate xml; pub mod parse; pub mod serialize; use clap::{App, Arg}; use std::fs::File; use std::io::BufReader; fn main() { let args = App::new("script-extractor") .version(&crate_version!()) .about("Parse movie scripts (pdf) to a structured format (xml)") .arg(Arg::with_name("input-file") .help("xml extracted using 'pdftohtml -xml script.pdf'") .index(1) .required(true) .validator(check_file_exists)) .get_matches(); let input_file = args.value_of("input-file").unwrap(); let file_reader = File::open(input_file).expect("Cannot open file"); let buffered_file_reader = Box::new(BufReader::new(file_reader)); let scenes = parse::parse_script(buffered_file_reader); serialize::xml::format_script(&scenes, &mut std::io::stdout()).unwrap(); } fn check_file_exists(file_name: String) -> Result<(), String> { if let Ok(metadata) = std::fs::metadata(&file_name) { if metadata.is_file() && !metadata.permissions().readonly() { Ok(()) } else { Err(format!("Cannot read file '{}'", file_name)) } } else { Err(format!("File '{}' not found", file_name)) } }
#[macro_use] extern crate clap; extern crate regex; extern crate xml; pub mod parse; pub mod serialize; use clap::{App, Arg}; use std::fs::File; use std::io::{BufReader, Read}; fn main() { let args = App::new("script-extractor") .version(&crate_version!()) .about("Parse movie scripts (pdf) to a structured format (xml)") .arg(Arg::with_name("input-file") .help("xml extracted using 'pdftohtml -xml script.pdf'") .index(1) .validator(check_file_exists)) .get_matches(); let input: Box<Read> = if let Some(input_file) = args.value_of("input-file") { let file_reader = File::open(input_file).expect("Cannot open input-file"); Box::new(BufReader::new(file_reader)) } else { Box::new(BufReader::new(std::io::stdin())) }; let scenes = parse::parse_script(input); serialize::xml::format_script(&scenes, &mut std::io::stdout()).unwrap(); } fn check_file_exists(file_name: String) -> Result<(), String> { if let Ok(metadata) = std::fs::metadata(&file_name) { if metadata.is_file() && !metadata.permissions().readonly() { Ok(()) } else { Err(format!("Cannot read file '{}'", file_name)) } } else { Err(format!("File '{}' not found", file_name)) } }
Add implementation with tuple usage
fn main() { let length = 50; let width = 30; println!( "Area of rectangle with length: {} and width: {} is equal to: {}", length, width, area(length, width) ); } fn area(length: u32, width: u32) -> u32 { length * width }
fn main() { let length = 50; let width = 30; println!( "Area of rectangle with length: {} and width: {} is equal to: {}", length, width, area(length, width) ); let rect = (length, width); println!( "Area of rectangle with length: {} and width: {} is equal to: {}", rect.0, rect.1, area_with_tuple(rect) ); } fn area(length: u32, width: u32) -> u32 { length * width } fn area_with_tuple(dimensions: (u32, u32)) -> u32 { dimensions.0 * dimensions.1 }
Add doc comment for tokio crate
extern crate dbus; extern crate futures; extern crate tokio_core; extern crate mio; /// Tokio integration for dbus /// /// For examples to get you started, see the examples directory and the Readme. pub mod tree; mod adriver; pub use adriver::{AConnection, AMessageStream, AMethodCall};
extern crate dbus; extern crate futures; extern crate tokio_core; extern crate mio; //! Tokio integration for dbus //! //! What's currently working is: //! //! * Client: Make method calls and wait asynchronously for them to be replied to - see `AConnection::method_call` //! * Get a stream of incoming messages (so you can listen to signals etc) - see `AConnection::messages` //! * Server: Make a tree handle that stream of incoming messages - see `tree::ATreeServer` //! * Server: Add asynchronous methods to the tree - in case you cannot reply right away, //! you can return a future that will reply when that future resolves - see `tree::AFactory::amethod` //! //! For examples to get you started, see the examples directory and the Readme. pub mod tree; mod adriver; pub use adriver::{AConnection, AMessageStream, AMethodCall};
Add error codes Switch to using Result in io functions Remove outdated ZFS scheme, as the ZFS app has new development
use super::*; use std::fs::File; use std::io::Read; pub enum OpenStatus { Ok, NotFound, } impl Editor { /// Open a file pub fn open(&mut self, path: &str) -> OpenStatus { self.status_bar.file = path.to_string(); if let Some(mut file) = File::open(path) { let mut con = String::new(); file.read_to_string(&mut con); self.text = con.lines() .map(|x| x.chars().collect::<VecDeque<char>>()) .collect::<VecDeque<VecDeque<char>>>(); OpenStatus::Ok } else { OpenStatus::NotFound } } }
use super::*; use std::fs::File; use std::io::Read; pub enum OpenStatus { Ok, NotFound, } impl Editor { /// Open a file pub fn open(&mut self, path: &str) -> OpenStatus { self.status_bar.file = path.to_string(); if let Some(mut file) = File::open(path).ok() { let mut con = String::new(); file.read_to_string(&mut con); self.text = con.lines() .map(|x| x.chars().collect::<VecDeque<char>>()) .collect::<VecDeque<VecDeque<char>>>(); OpenStatus::Ok } else { OpenStatus::NotFound } } }
Implement a simple constructor for Repository
use object_id::ObjectId; use tag::Tag; use branch::Branch; use reference::Reference; use pack_index::PackIndex; pub struct Repository { pub path: String, pub wc_path: String, pub tags: Vec<Tag>, pub branches: Vec<Branch>, pub references: Vec<Reference>, pub pack_indexes: Vec<PackIndex>, }
use object_id::ObjectId; use tag::Tag; use branch::Branch; use reference::Reference; use pack_index::PackIndex; pub struct Repository { pub path: String, pub wc_path: String, pub tags: Vec<Tag>, pub branches: Vec<Branch>, pub references: Vec<Reference>, pub pack_indexes: Vec<PackIndex>, } impl Repository { pub fn new(path: &str) -> Repository { Repository { path: path.to_string() + ".git/", wc_path: path.to_string(), tags: Vec::new(), branches: Vec::new(), references: Vec::new(), pack_indexes: Vec::new(), } } }
Update to last upstream version
use crate::context::parse_lint_and_tool_name; use rustc_span::{with_default_session_globals, Symbol}; #[test] fn parse_lint_no_tool() { with_default_session_globals(|| assert_eq!(parse_lint_and_tool_name("foo"), (None, "foo"))); } #[test] fn parse_lint_with_tool() { with_default_session_globals(|| { assert_eq!(parse_lint_and_tool_name("clippy::foo"), (Some(Symbol::intern("clippy")), "foo")) }); } #[test] fn parse_lint_multiple_path() { with_default_session_globals(|| { assert_eq!( parse_lint_and_tool_name("clippy::foo::bar"), (Some(Symbol::intern("clippy")), "foo::bar") ) }); }
use crate::context::parse_lint_and_tool_name; use rustc_span::{create_default_session_globals_then, Symbol}; #[test] fn parse_lint_no_tool() { create_default_session_globals_then(|| { assert_eq!(parse_lint_and_tool_name("foo"), (None, "foo")) }); } #[test] fn parse_lint_with_tool() { create_default_session_globals_then(|| { assert_eq!(parse_lint_and_tool_name("clippy::foo"), (Some(Symbol::intern("clippy")), "foo")) }); } #[test] fn parse_lint_multiple_path() { create_default_session_globals_then(|| { assert_eq!( parse_lint_and_tool_name("clippy::foo::bar"), (Some(Symbol::intern("clippy")), "foo::bar") ) }); }
Correct event relativization in Panel
use Printer; use vec::Vec2; use view::{View, ViewWrapper}; /// Draws a border around a wrapped view. pub struct Panel<V: View> { view: V, } impl<V: View> Panel<V> { /// Creates a new panel around the given view. pub fn new(view: V) -> Self { Panel { view: view } } } impl<V: View> ViewWrapper for Panel<V> { wrap_impl!(self.view: V); fn wrap_required_size(&mut self, req: Vec2) -> Vec2 { // TODO: make borders conditional? let req = req.saturating_sub((2, 2)); self.view.required_size(req) + (2, 2) } fn wrap_draw(&self, printer: &Printer) { printer.print_box((0, 0), printer.size, true); self.view.draw(&printer.sub_printer( (1, 1), printer.size.saturating_sub((2, 2)), true, )); } fn wrap_layout(&mut self, size: Vec2) { self.view.layout(size.saturating_sub((2, 2))); } }
use Printer; use event::{Event, EventResult}; use vec::Vec2; use view::{View, ViewWrapper}; /// Draws a border around a wrapped view. pub struct Panel<V: View> { view: V, } impl<V: View> Panel<V> { /// Creates a new panel around the given view. pub fn new(view: V) -> Self { Panel { view: view } } } impl<V: View> ViewWrapper for Panel<V> { wrap_impl!(self.view: V); fn wrap_on_event(&mut self, event: Event) -> EventResult { self.view.on_event(event.relativized((1, 1))) } fn wrap_required_size(&mut self, req: Vec2) -> Vec2 { // TODO: make borders conditional? let req = req.saturating_sub((2, 2)); self.view.required_size(req) + (2, 2) } fn wrap_draw(&self, printer: &Printer) { printer.print_box((0, 0), printer.size, true); self.view.draw(&printer.sub_printer( (1, 1), printer.size.saturating_sub((2, 2)), true, )); } fn wrap_layout(&mut self, size: Vec2) { self.view.layout(size.saturating_sub((2, 2))); } }
Add is_tag clap validator helper
//! Functions to be used for clap::Arg::validator() //! to validate arguments use std::path::PathBuf; use boolinator::Boolinator; pub fn is_file(s: String) -> Result<(), String> { PathBuf::from(s.clone()).is_file().as_result((), format!("Not a File: {}", s)) } pub fn is_directory(s: String) -> Result<(), String> { PathBuf::from(s.clone()).is_dir().as_result((), format!("Not a Directory: {}", s)) } pub fn is_integer(s: String) -> Result<(), String> { use std::str::FromStr; let i : Result<i64, _> = FromStr::from_str(&s); i.map(|_| ()).map_err(|_| format!("Not an integer: {}", s)) } pub fn is_url(s: String) -> Result<(), String> { use url::Url; Url::parse(&s).map(|_| ()).map_err(|_| format!("Not a URL: {}", s)) }
//! Functions to be used for clap::Arg::validator() //! to validate arguments use std::path::PathBuf; use boolinator::Boolinator; pub fn is_file(s: String) -> Result<(), String> { PathBuf::from(s.clone()).is_file().as_result((), format!("Not a File: {}", s)) } pub fn is_directory(s: String) -> Result<(), String> { PathBuf::from(s.clone()).is_dir().as_result((), format!("Not a Directory: {}", s)) } pub fn is_integer(s: String) -> Result<(), String> { use std::str::FromStr; let i : Result<i64, _> = FromStr::from_str(&s); i.map(|_| ()).map_err(|_| format!("Not an integer: {}", s)) } pub fn is_url(s: String) -> Result<(), String> { use url::Url; Url::parse(&s).map(|_| ()).map_err(|_| format!("Not a URL: {}", s)) } pub fn is_tag(s: String) -> Result<(), String> { use regex::Regex; lazy_static! { static ref TAG_RE : Regex = Regex::new("[:alpha:][:word:]*").unwrap(); } TAG_RE .is_match(&s) .as_result((), format!("Not a valid Tag: '{}' - Valid is [a-zA-Z][0-9a-zA-Z]*", s)) }
Swap dummy fib benchmark for opening/closing files
#[macro_use] extern crate criterion; use criterion::Criterion; fn fib(n: u64) -> u64 { let mut a = 0u64; let mut b = 1u64; let mut c = 0u64; if n == 0 { return 0 } for _ in 0..(n+1) { c = a + b; a = b; b = c; } b } fn criterion_benchmark(c: &mut Criterion) { c.bench_function("fib 20", |b| b.iter(|| fib(20))); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
#[macro_use] extern crate criterion; extern crate fitsio; use criterion::Criterion; fn criterion_benchmark(c: &mut Criterion) { c.bench_function("opening and closing files", |b| b.iter(|| { let filename = "../testdata/full_example.fits"; { let f = fitsio::FitsFile::open(filename).unwrap(); /* Implicit drop */ } })); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
Rewrite RFC 5161 parser with function parsers
//! //! https://tools.ietf.org/html/rfc5161 //! //! The IMAP ENABLE Extension //! // rustfmt doesn't do a very good job on nom parser invocations. #![cfg_attr(rustfmt, rustfmt_skip)] use crate::types::*; use crate::parser::core::atom; // The ENABLED response lists capabilities that were enabled in response // to a ENABLE command. // [RFC5161 - 3.2 The ENABLED Response](https://tools.ietf.org/html/rfc5161#section-3.2) named!(pub (crate) resp_enabled<Response>, map!( enabled_data, Response::Capabilities )); named!(enabled_data<Vec<Capability>>, do_parse!( tag_no_case!("ENABLED") >> capabilities: many0!(preceded!(char!(' '), capability)) >> (capabilities) )); named!(capability<Capability>, map!(atom, Capability::Atom) );
//! //! https://tools.ietf.org/html/rfc5161 //! //! The IMAP ENABLE Extension //! use nom::{ bytes::streaming::tag_no_case, character::streaming::char, combinator::map, multi::many0, sequence::{preceded, tuple}, IResult, }; use crate::parser::core::atom; use crate::types::*; // The ENABLED response lists capabilities that were enabled in response // to a ENABLE command. // [RFC5161 - 3.2 The ENABLED Response](https://tools.ietf.org/html/rfc5161#section-3.2) pub(crate) fn resp_enabled(i: &[u8]) -> IResult<&[u8], Response> { map(enabled_data, Response::Capabilities)(i) } fn enabled_data(i: &[u8]) -> IResult<&[u8], Vec<Capability>> { let (i, (_, capabilities)) = tuple(( tag_no_case("ENABLED"), many0(preceded(char(' '), capability)), ))(i)?; Ok((i, capabilities)) } fn capability(i: &[u8]) -> IResult<&[u8], Capability> { map(atom, Capability::Atom)(i) }
Write top level module docs.
extern crate num; extern crate oxcable; pub mod adsr; pub mod delay; pub mod dynamics; pub mod reverb; pub mod tremolo;
//! Basic audio filters for making music with Rust. //! //! This is an extension to the //! [`oxcable` framework](https://github.com/oxcable/oxcable). These devices are //! designed to be used with the basic tools provided in the framework. See the //! core crate for further details. extern crate num; extern crate oxcable; pub mod adsr; pub mod delay; pub mod dynamics; pub mod reverb; pub mod tremolo;
Update the example to use the collection function.
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. use fleetspeak::client::Packet; fn main() -> std::io::Result<()> { fleetspeak::client::startup("0.0.1")?; loop { let request = fleetspeak::client::receive::<String>()?.data; let response = format!("Hello {}!", request); fleetspeak::client::send(Packet { service: String::from("greeter"), kind: None, data: response, })?; } }
// Copyright 2020 Google LLC // // Use of this source code is governed by an MIT-style license that can be found // in the LICENSE file or at https://opensource.org/licenses/MIT. use std::time::Duration; use fleetspeak::client::Packet; fn main() -> std::io::Result<()> { fleetspeak::client::startup("0.0.1")?; loop { let packet = fleetspeak::client::collect(Duration::from_secs(1))?; let request: String = packet.data; let response: String = format!("Hello {}!", request); fleetspeak::client::send(Packet { service: String::from("greeter"), kind: None, data: response, })?; } }
Add `from_gl()` and `gl_enum()` to all `gl_enum!` types
// Used to specify checks that shouldn't fail (but might in unsafe) macro_rules! dbg_gl_error { ($($pat:pat => $msg:expr),*) => { if cfg!(debug_assertions) { let err = $crate::Context::get_error(); match err { $(Some($pat) => { panic!("OpenGL error {:?} - {}", err, $msg) }),* None => { } } } } } // Used to specify checks that should *never* be able to fail (even in unsafe!) macro_rules! dbg_gl_sanity_check { ($($pat:pat => $msg:expr),*) => { dbg_gl_error! { $($pat => concat!("Sanity check failed: ", $msg)),* } } } macro_rules! gl_enum { ( pub gl_enum $name:ident { $($variant:ident as $const_name:ident = $value:expr),+ } ) => { #[derive(Debug, Clone, Copy)] pub enum $name { $($variant = $value as isize),+ } $(pub const $const_name: $name = $name::$variant;)+ } }
// Used to specify checks that shouldn't fail (but might in unsafe) macro_rules! dbg_gl_error { ($($pat:pat => $msg:expr),*) => { if cfg!(debug_assertions) { let err = $crate::Context::get_error(); match err { $(Some($pat) => { panic!("OpenGL error {:?} - {}", err, $msg) }),* None => { } } } } } // Used to specify checks that should *never* be able to fail (even in unsafe!) macro_rules! dbg_gl_sanity_check { ($($pat:pat => $msg:expr),*) => { dbg_gl_error! { $($pat => concat!("Sanity check failed: ", $msg)),* } } } macro_rules! gl_enum { ( pub gl_enum $name:ident { $($variant:ident as $const_name:ident = $value:expr),+ } ) => { #[derive(Debug, Clone, Copy)] pub enum $name { $($variant = $value as isize),+ } $(pub const $const_name: $name = $name::$variant;)+ #[allow(dead_code)] impl $name { pub fn from_gl(gl_enum: $crate::gl::types::GLenum) -> Result<Self, ()> { match gl_enum { $(x if x == $value => { Ok($name::$variant) },)+ _ => { Err(()) } } } pub fn gl_enum(&self) -> $crate::gl::types::GLenum { *self as $crate::gl::types::GLenum } } } }
Rename ptr sized integer variants
#![no_main] use arbitrary::Arbitrary; use libfuzzer_sys::fuzz_target; #[derive(Arbitrary, Debug)] enum IntegerInput { I8(i8), U8(u8), I16(i16), U16(u16), I32(i32), U32(u32), I64(i64), U64(u64), I128(i128), U128(u128), ISIZE(isize), USIZE(usize), } fuzz_target!(|input: IntegerInput| { let mut buffer = itoa::Buffer::new(); match input { IntegerInput::I8(val) => buffer.format(val), IntegerInput::U8(val) => buffer.format(val), IntegerInput::I16(val) => buffer.format(val), IntegerInput::U16(val) => buffer.format(val), IntegerInput::I32(val) => buffer.format(val), IntegerInput::U32(val) => buffer.format(val), IntegerInput::I64(val) => buffer.format(val), IntegerInput::U64(val) => buffer.format(val), IntegerInput::I128(val) => buffer.format(val), IntegerInput::U128(val) => buffer.format(val), IntegerInput::ISIZE(val) => buffer.format(val), IntegerInput::USIZE(val) => buffer.format(val), }; });
#![no_main] use arbitrary::Arbitrary; use libfuzzer_sys::fuzz_target; #[derive(Arbitrary, Debug)] enum IntegerInput { I8(i8), U8(u8), I16(i16), U16(u16), I32(i32), U32(u32), I64(i64), U64(u64), I128(i128), U128(u128), Isize(isize), Usize(usize), } fuzz_target!(|input: IntegerInput| { let mut buffer = itoa::Buffer::new(); match input { IntegerInput::I8(val) => buffer.format(val), IntegerInput::U8(val) => buffer.format(val), IntegerInput::I16(val) => buffer.format(val), IntegerInput::U16(val) => buffer.format(val), IntegerInput::I32(val) => buffer.format(val), IntegerInput::U32(val) => buffer.format(val), IntegerInput::I64(val) => buffer.format(val), IntegerInput::U64(val) => buffer.format(val), IntegerInput::I128(val) => buffer.format(val), IntegerInput::U128(val) => buffer.format(val), IntegerInput::Isize(val) => buffer.format(val), IntegerInput::Usize(val) => buffer.format(val), }; });
Make the wrapper time_ns public.
extern crate time; use time::precise_time_ns; fn time_ns() -> u64 { precise_time_ns() } #[macro_export] macro_rules! stack { ($name:expr, $work:expr) => { { let work = {|| $work}; println!("Push {}", $name); let before = $crate::time_ns(); let value = work(); let after = $crate::time_ns(); println!("Pop {} spent {}ns.", $name, after-before); value } } } #[test] fn it_works() { stack!("all", 3+4); }
extern crate time; use time::precise_time_ns; pub fn time_ns() -> u64 { precise_time_ns() } #[macro_export] macro_rules! stack { ($name:expr, $work:expr) => { { let work = {|| $work}; println!("Push {}", $name); let before = $crate::time_ns(); let value = work(); let after = $crate::time_ns(); println!("Pop {} spent {}ns.", $name, after-before); value } } } #[test] fn it_works() { stack!("all", 3+4); }
Add bench for zcr desc
#![feature(test)] // TODO use cfg(bench) to make pub functions not-pub depending on context #[cfg(test)] mod test { extern crate test; use bliss_rs::timbral::SpectralDesc; use test::Bencher; #[bench] fn bench_spectral_desc(b: &mut Bencher) { let mut spectral_desc = SpectralDesc::new(10); let chunk = vec![0.; 512]; b.iter(|| { spectral_desc.do_(&chunk); }); } }
#![feature(test)] // TODO use cfg(bench) to make pub functions not-pub depending on context #[cfg(test)] mod test { extern crate test; use bliss_rs::timbral::SpectralDesc; use bliss_rs::timbral::ZeroCrossingRateDesc; use test::Bencher; #[bench] fn bench_spectral_desc(b: &mut Bencher) { let mut spectral_desc = SpectralDesc::new(10); let chunk = vec![0.; 512]; b.iter(|| { spectral_desc.do_(&chunk); }); } #[bench] fn bench_zcr_desc(b: &mut Bencher) { let mut zcr_desc = ZeroCrossingRateDesc::new(10); let chunk = vec![0.; 512]; b.iter(|| { zcr_desc.do_(&chunk); }); } }
Print transaction status in functional-tests error message.
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 pub use anyhow::{anyhow, bail, format_err, Error, Result}; use libra_types::{transaction::TransactionOutput, vm_error::VMStatus}; use thiserror::Error; /// Defines all errors in this crate. #[derive(Clone, Debug, Error)] pub enum ErrorKind { #[error("an error occurred when executing the transaction")] VMExecutionFailure(TransactionOutput), #[error("the transaction was discarded")] DiscardedTransaction(TransactionOutput), #[error("the checker has failed to match the directives against the output")] CheckerFailure, #[error("VerificationError({0:?})")] VerificationError(VMStatus), #[error("other error: {0}")] #[allow(dead_code)] Other(String), }
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 pub use anyhow::{anyhow, bail, format_err, Error, Result}; use libra_types::{transaction::TransactionOutput, vm_error::VMStatus}; use thiserror::Error; /// Defines all errors in this crate. #[derive(Clone, Debug, Error)] pub enum ErrorKind { #[error("an error occurred when executing the transaction, txn status {:?}", .0.status())] VMExecutionFailure(TransactionOutput), #[error("the transaction was discarded")] DiscardedTransaction(TransactionOutput), #[error("the checker has failed to match the directives against the output")] CheckerFailure, #[error("VerificationError({0:?})")] VerificationError(VMStatus), #[error("other error: {0}")] #[allow(dead_code)] Other(String), }
Make it work for simple additions
fn main(expr: &str) -> i32 { let result = 0; for c in expr.chars() { match c { '0' ... '9' => println!("number"), ' ' => println!("space"), '+' => println!("plus"), _ => panic!("unsupported character") } } return result; } #[test] fn it_adds() { let result = main("+1 2"); assert_eq!(result, 3); }
fn main(expr: &str) -> i32 { let mut result = 0; let mut stack:Vec<i32> = Vec::new(); for token in expr.split_whitespace() { let wrapped_operand = token.parse::<i32>(); let is_operator = wrapped_operand.is_err(); if is_operator { // xxxFlorent: Any way to destructure like this? Not sure of what I am doing below // let [ operand1, operand2 ] = stack.drain((token.len() - 3)..).collect(); let operand1 = stack.pop().expect("expected i32 values only in stack"); let operand2 = stack.pop().expect("expected i32 values only in stack"); result += match token { "+" => operand1 + operand2, _ => panic!("unsupported operator") } } else { stack.push(wrapped_operand.unwrap()); } } return result; } #[test] fn it_adds() { let result = main("1 2 +"); assert_eq!(result, 3); } #[test] #[should_panic] fn it_panics_for_unsupported_operators() { main("1 2 ="); // xxxFlorent: How to test the panic message is right? }
Add sample git command invocation
use std::env; use std::path::PathBuf; #[macro_use] extern crate log; mod git; fn get_current_dir() -> PathBuf { env::current_dir().unwrap_or_else(|e| { panic!("Get current dir expected to succeed. Error: {}", e); }) } fn main() { match git::stash(&get_current_dir()) { Ok(stash) => println!("Stash: {}", stash), Err(e) => panic!("Error: {}", e), } }
use std::env; use std::path::PathBuf; #[macro_use] extern crate log; mod git; fn get_current_dir() -> PathBuf { env::current_dir().unwrap_or_else(|e| { panic!("Get current dir expected to succeed. Error: {}", e); }) } fn main() { match git::stash(&get_current_dir()) { Ok(stash) => println!("Stash: {}", stash), Err(e) => panic!("Error: {}", e), } match git::reset(&get_current_dir(), "HEAD") { Ok(reset) => println!("reset: {}", reset), Err(e) => panic!("Error: {}", e), } }
Add allow_remote parameter to content fetching endpoint.
//! Endpoints for the media repository. //! [GET /_matrix/media/r0/download/{serverName}/{mediaId}](https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-media-r0-download-servername-mediaid) use ruma_api::ruma_api; ruma_api! { metadata { description: "Retrieve content from the media store.", method: GET, name: "get_media_content", path: "/_matrix/media/r0/download/:server_name/:media_id", rate_limited: false, requires_authentication: false, } request { /// The media ID from the mxc:// URI (the path component). #[ruma_api(path)] pub media_id: String, /// The server name from the mxc:// URI (the authoritory component). #[ruma_api(path)] pub server_name: String, } response { /// The content that was previously uploaded. #[ruma_api(raw_body)] pub file: Vec<u8>, /// The content type of the file that was previously uploaded. #[ruma_api(header = CONTENT_TYPE)] pub content_type: String, /// The name of the file that was previously uploaded, if set. #[ruma_api(header = CONTENT_DISPOSITION)] pub content_disposition: String, } }
//! Endpoints for the media repository. //! [GET /_matrix/media/r0/download/{serverName}/{mediaId}](https://matrix.org/docs/spec/client_server/r0.4.0.html#get-matrix-media-r0-download-servername-mediaid) use ruma_api::ruma_api; ruma_api! { metadata { description: "Retrieve content from the media store.", method: GET, name: "get_media_content", path: "/_matrix/media/r0/download/:server_name/:media_id", rate_limited: false, requires_authentication: false, } request { /// The media ID from the mxc:// URI (the path component). #[ruma_api(path)] pub media_id: String, /// The server name from the mxc:// URI (the authoritory component). #[ruma_api(path)] pub server_name: String, /// Whether to fetch media deemed remote. /// Used to prevent routing loops. Defaults to `true`. #[ruma_api(query)] pub allow_remote: Option<bool>, } response { /// The content that was previously uploaded. #[ruma_api(raw_body)] pub file: Vec<u8>, /// The content type of the file that was previously uploaded. #[ruma_api(header = CONTENT_TYPE)] pub content_type: String, /// The name of the file that was previously uploaded, if set. #[ruma_api(header = CONTENT_DISPOSITION)] pub content_disposition: String, } }
Add an example of how to iterate through child nodes.
extern crate radix_trie; use radix_trie::Trie; fn main() { let mut t = Trie::new(); t.insert("a", 5); t.insert("b", 6); t.insert("c", 50); let sum = t.child_iter().fold(0, |acc, c| { println!("{:#?}", c); acc + *c.value().unwrap_or(&0) }); println!("{}", sum); }
extern crate radix_trie; use radix_trie::Trie; fn main() { let mut t = Trie::new(); t.insert("z", 2); t.insert("aba", 5); t.insert("abb", 6); t.insert("abc", 50); // This is a bit of a hack that relies on knowing the binary representation of // strings... "abd" works, but "abz" doesn't... let ab_sum = t.get_raw_ancestor(&"abd").child_iter().fold(0, |acc, c| { println!("Iterating over child with value: {:?}", c.value()); acc + *c.value().unwrap_or(&0) }); println!("{}", ab_sum); assert_eq!(ab_sum, 5 + 6 + 50); }
Fix compile test from updated nightly
extern crate gluon; use gluon::{new_vm, Compiler}; fn main() { let vm = new_vm(); let _ = Compiler::new().run_expr::<&str>(&vm, "", r#" "test" "#); //~^ the trait bound `for<'value> &str: gluon::gluon_vm::api::Getable<'_, 'value>` is not satisfied }
extern crate gluon; use gluon::{new_vm, Compiler}; fn main() { let vm = new_vm(); let _ = Compiler::new().run_expr::<&str>(&vm, "", r#" "test" "#); //~^ mismatched types [E0308] }
Update to Rust nightly 2015-03-31
/* * Copyright 2015 Nathan Fiedler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // TODO: should be able to remove these once the API stabilizes #![feature(collections)] // to_lowercase() #![feature(core)] // std::error::Error, num::from_str_radix pub mod atom; pub mod lexer; pub mod sequence;
/* * Copyright 2015 Nathan Fiedler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // TODO: should be able to remove these once the API stabilizes #![allow(deprecated)] // num::from_str_radix #![feature(collections)] // to_lowercase() #![feature(core)] // std::error::Error, num::from_str_radix pub mod atom; pub mod lexer; pub mod sequence;
Move demo app’s unsafe code into a safe function
#[cfg(not(windows))] compile_error!("This demo only runs on Windows."); extern crate directcomposition; extern crate winit; use winit::os::windows::WindowExt; fn main() { let mut events_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Hello, world!") .with_dimensions(1024, 768) .build(&events_loop) .unwrap(); let composition = unsafe { directcomposition::DirectComposition::new(window.get_hwnd() as _).unwrap() }; let visual = composition.create_d3d_visual(300, 200).unwrap(); visual.set_offset_x(100.).unwrap(); visual.set_offset_y(50.).unwrap(); composition.commit().unwrap(); let green_rgba = [0., 0.5, 0., 1.]; visual.render_and_present_solid_frame(&composition, &green_rgba).unwrap(); if std::env::var_os("INIT_ONLY").is_some() { return } events_loop.run_forever(|event| match event { winit::Event::WindowEvent { event: winit::WindowEvent::Closed, .. } => { winit::ControlFlow::Break } _ => winit::ControlFlow::Continue, }); }
#[cfg(not(windows))] compile_error!("This demo only runs on Windows."); extern crate directcomposition; extern crate winit; use directcomposition::DirectComposition; use winit::os::windows::WindowExt; fn main() { let mut events_loop = winit::EventsLoop::new(); let window = winit::WindowBuilder::new() .with_title("Hello, world!") .with_dimensions(1024, 768) .build(&events_loop) .unwrap(); let composition = direct_composition_from_window(&window); let visual = composition.create_d3d_visual(300, 200).unwrap(); visual.set_offset_x(100.).unwrap(); visual.set_offset_y(50.).unwrap(); composition.commit().unwrap(); let green_rgba = [0., 0.5, 0., 1.]; visual.render_and_present_solid_frame(&composition, &green_rgba).unwrap(); if std::env::var_os("INIT_ONLY").is_some() { return } events_loop.run_forever(|event| match event { winit::Event::WindowEvent { event: winit::WindowEvent::Closed, .. } => { winit::ControlFlow::Break } _ => winit::ControlFlow::Continue, }); } fn direct_composition_from_window(window: &winit::Window) -> DirectComposition { unsafe { DirectComposition::new(window.get_hwnd() as _).unwrap() } }
Add basic packet read, including unsafe conversion
//! Contains code to handle an IPC channel which is issuing commands. use std::io::prelude::*; use rustc_serialize::Decodable; use rustc_serialize::json::{Json, ToJson, Decoder, EncoderError}; use unix_socket::UnixStream; /// Reasons a client message might be erroneous #[derive(Debug, Clone)] enum ResponseError { /// Connection was closed ConnectionClosed, /// Json was invalid InvalidJson(EncoderError) } /// Receives a packet from the given stream. fn receive_packet(stream: &mut UnixStream) -> Result<Json, ResponseError> { Err(ResponseError::ConnectionClosed) } pub fn handle_client(mut stream: UnixStream) { println!("Starting connection."); // Listen for starting connection } fn command(mut stream: UnixStream) { } fn event(mut stream: UnixStream) { }
//! Contains code to handle an IPC channel which is issuing commands. use std::io::Error as IOError; use std::io::prelude::*; use rustc_serialize::Decodable; use rustc_serialize::json::{Json, ToJson, Decoder, ParserError, EncoderError}; use unix_socket::UnixStream; /// Reasons a client message might be erroneous #[derive(Debug)] enum ResponseError { /// Connection was closed ConnectionClosed, /// Some bytes dun goofed InvalidString, /// There were IO issues IO(IOError), /// Json was invalid InvalidJson(ParserError) } /// Receives a packet from the given stream. fn receive_packet(stream: &mut Read) -> Result<Json, ResponseError> { let mut buffer = [0u8; 4]; try!(stream.read_exact(&mut buffer).map_err(ResponseError::IO)); // This is what the byteorder crate does (needs testing) let len = u32::from_be(unsafe { buffer.as_ptr() as *const u32 } as u32); trace!("Listening for packet of length {}", len); return Json::from_reader(&mut stream.take(len as u64)) .map_err(ResponseError::InvalidJson); } pub fn handle_client(mut stream: UnixStream) { println!("Starting connection."); // Listen for starting connection } fn command(mut stream: UnixStream) { } fn event(mut stream: UnixStream) { }
Remove prerequisite checks covered by being able to run the code
use std::io::ErrorKind; use std::process::Command; use structopt::StructOpt; mod commands; /// Personal CLI. #[derive(StructOpt)] enum Commands { /// Reproduce my computer's configuration. Setup, /// Upgrade what's installed on my computer. Upgrade, /// Clean up my computer's state. End, /// Start a study session. Study, } fn main() { match Command::new("which").arg("killall").output() { Ok(_) => (), Err(error) => match error.kind() { ErrorKind::NotFound => panic!("A Unix environment is required."), other_error => panic!("There was a problem: {:?}", other_error), }, }; match Command::new("brew").output() { Ok(_) => (), Err(error) => match error.kind() { ErrorKind::NotFound => panic!("Homebrew is required."), other_error => panic!("There was a problem: {:?}", other_error), }, } match Commands::from_args() { Commands::Setup => commands::setup(), Commands::Upgrade => commands::upgrade(), Commands::End => commands::end(), Commands::Study => commands::study(), } println!("Finished."); }
use structopt::StructOpt; mod commands; /// Personal CLI. #[derive(StructOpt)] enum Commands { /// Reproduce my computer's configuration. Setup, /// Upgrade what's installed on my computer. Upgrade, /// Clean up my computer's state. End, /// Start a study session. Study, } fn main() { match Commands::from_args() { Commands::Setup => commands::setup(), Commands::Upgrade => commands::upgrade(), Commands::End => commands::end(), Commands::Study => commands::study(), } println!("Finished."); }
Fix formats_source test requiring rustfmt.
use cargo_test_support::compare::assert_ui; use cargo_test_support::prelude::*; use cargo_test_support::Project; use cargo_test_support::curr_dir; #[cargo_test(requires_rustfmt)] fn formats_source() { let project = Project::from_template(curr_dir!().join("in")); let project_root = &project.root(); snapbox::cmd::Command::cargo_ui() .arg_line("init --lib --vcs none") .current_dir(project_root) .assert() .success() .stdout_matches_path(curr_dir!().join("stdout.log")) .stderr_matches_path(curr_dir!().join("stderr.log")); assert_ui().subset_matches(curr_dir!().join("out"), project_root); }
use cargo_test_support::compare::assert_ui; use cargo_test_support::prelude::*; use cargo_test_support::{process, Project}; use cargo_test_support::curr_dir; #[cargo_test] fn formats_source() { // This cannot use `requires_rustfmt` because rustfmt is not available in // the rust-lang/rust environment. Additionally, if running cargo without // rustup (but with rustup installed), this test also fails due to HOME // preventing the proxy from choosing a toolchain. if let Err(e) = process("rustfmt").arg("-V").exec_with_output() { eprintln!("skipping test, rustfmt not available:\n{e:?}"); return; } let project = Project::from_template(curr_dir!().join("in")); let project_root = &project.root(); snapbox::cmd::Command::cargo_ui() .arg_line("init --lib --vcs none") .current_dir(project_root) .assert() .success() .stdout_matches_path(curr_dir!().join("stdout.log")) .stderr_matches_path(curr_dir!().join("stderr.log")); assert_ui().subset_matches(curr_dir!().join("out"), project_root); }
Send debug statements to stderr
macro_rules! w { ($buf:expr, $to_w:expr) => { match $buf.write_all($to_w) { Ok(..) => (), Err(..) => panic!("Failed to write to generated file"), } }; } #[cfg(feature = "debug")] macro_rules! debug { ($($arg:tt)*) => { print!("[{:>w$}] \t", module_path!(), w = 28); println!($($arg)*) } } #[cfg(not(feature = "debug"))] macro_rules! debug { ($($arg:tt)*) => {}; }
macro_rules! w { ($buf:expr, $to_w:expr) => { match $buf.write_all($to_w) { Ok(..) => (), Err(..) => panic!("Failed to write to generated file"), } }; } #[cfg(feature = "debug")] macro_rules! debug { ($($arg:tt)*) => { eprint!("[{:>w$}] \t", module_path!(), w = 28); eprintln!($($arg)*) } } #[cfg(not(feature = "debug"))] macro_rules! debug { ($($arg:tt)*) => {}; }
Set tweet filter to include link
#[derive(Deserialize, Debug)] pub struct Tweet { pub id: i64, pub text: String, } use std::fmt::{self, Display, Formatter}; impl Display for Tweet { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut txt = self.text.clone(); if let Some(pos) = txt.find("http") { txt = txt[..pos].to_owned(); } write!(f, "{}", txt) } }
#[derive(Deserialize, Debug)] pub struct Tweet { pub id: i64, pub text: String, } use std::fmt::{self, Display, Formatter}; impl Display for Tweet { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut txt = self.text.clone(); if let Some(pos) = txt.find("#") { txt = txt[..pos].to_owned(); } write!(f, "{}", txt) } }
Add Window and Split to Commands
use std::path::Path; pub trait Command { fn call<S>(&self) -> Vec<S> where S: Into<String>; } pub struct Session { pub name: String, pub window_name: String, pub root_path: Path } impl Command for Session { fn call<S>(&self) -> Vec<S> where S: Into<String>, { vec!("new", "-d", "-s", &self.name, "-n", &self.window_name, "-c", &self.root_path.to_str().unwrap()) } }
use std::path::Path; pub trait Command { fn call<S>(&self) -> Vec<&str>; } pub struct Session { pub name: String, pub window_name: String, pub root_path: Path } impl Command for Session { fn call<S>(&self) -> Vec<&str> { vec!("new", "-d", "-s", &self.name, "-n", &self.window_name, "-c", &self.root_path.to_str().unwrap()) } } #[derive(Debug, Clone)] pub struct Window { pub session_name: String, pub name: String, // pub path: Path } impl Command for Window { fn call<S>(&self) -> Vec<&str> { vec!("new-window", "-t", &self.session_name, "-n", &self.name) } } #[derive(Debug, Clone)] pub struct Split { pub target: String, } impl Command for Split { fn call<S>(&self) -> Vec<&str> { vec!("split-window", "-t", &self.target) } }