commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
728cd69c3a751f0b30fb8321a443532661ad3aae
src/main.rs
src/main.rs
mod rooms; use std::io; fn move_to_next_room_if_possible<'a>(room: &'a rooms::Room, next_room: Option<&'a rooms::Room>, direction: &str) -> &'a rooms::Room { match next_room { Some(room) => {...
mod rooms; use std::io; fn move_to_next_room_if_possible<'a>(room: &'a rooms::Room, next_room: Option<&'a rooms::Room>, direction: &str) -> &'a rooms::Room { match next_room { Some(room) => {...
Replace if/else if block to match for checking command.
Replace if/else if block to match for checking command.
Rust
bsd-2-clause
donmccaughey/rust_rooms
3fdb0b05d8863c04e5a7831895fa07643a528355
src/main.rs
src/main.rs
//! Muxed. A tmux project manager with no runtime dependencies. extern crate getopts; extern crate libc; extern crate yaml_rust; extern crate rand; use std::env; mod tmux; mod command; mod project; use project::parser; use project::processor; /// The main execution method. /// Currently accepts a single option. The...
//! Muxed. A tmux project manager with no runtime dependencies. extern crate getopts; extern crate libc; extern crate yaml_rust; extern crate rand; use std::env; mod tmux; mod command; mod project; use project::parser; use project::processor; #[macro_export] macro_rules! try_or_err ( ($expr: expr) => ({ ...
Add the macro to assist with graceful exits.
Add the macro to assist with graceful exits. Major functions should return appropriate Result cases and propogate errors forward. At the front we want to provide helpful messaging and a graceful exit.
Rust
mit
brianp/muxed,brianp/muxed
3ee2a6940c04fe5dba850124f24ccd70e275a539
src/main.rs
src/main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate dotenv; extern crate libc; use std::{env, ptr}; use std::ffi::CString; use libc::{c_char, c_int}; /// Literally taken from the libstd /// (sys/unix/process.rs that is) fn make_argv(prog: &CString) -> *const *const libc::c_char { let...
#[macro_use] extern crate log; extern crate env_logger; extern crate dotenv; extern crate libc; use std::{env, ptr}; use std::ffi::CString; use libc::{c_char, c_int}; /// Literally taken from the libstd /// (sys/unix/process.rs that is) fn make_argv(prog: &CString) -> *const *const libc::c_char { let...
Return error code from execv
Return error code from execv This will only happen if the command can't be executed, e.g. it does not exist.
Rust
mit
badboy/dotenv-shell
b3c65ef04495e04506a1e6493744c355afd97dad
src/stream.rs
src/stream.rs
use metadata::{Metadata, StreamInfo, metadata_parser}; use frame::{frame_parser, Frame}; enum ParserState { Marker, Metadata, Frame, } pub struct Stream { pub info: StreamInfo, pub metadata: Vec<Metadata>, pub frames: Vec<Frame>, } named!(pub stream_parser <&[u8], Stream>, chain!( blocks: metadata_...
use nom::{ConsumerState, Move}; use metadata::{Metadata, StreamInfo, metadata_parser}; use frame::{frame_parser, Frame}; enum ParserState { Marker, Metadata, Frame, } pub struct Stream { pub info: StreamInfo, pub metadata: Vec<Metadata>, pub frames: Vec<Frame>, state: ParserState, consumer_state: Co...
Add the two different states to `Stream`
Add the two different states to `Stream`
Rust
bsd-3-clause
sourrust/flac
55946cf8068630366ca4b2cdf8d748ecb9e5fb71
gba/src/memory/io/types/interrupts.rs
gba/src/memory/io/types/interrupts.rs
use util::{bitfields, bits::Bits, primitive_enum}; bitfields! { /// 4000208h - IME - Interrupt Master Enable Register (R/W) /// Bit Expl. /// 0 Disable all interrupts (0=Disable All, 1=See [`InterruptEnable`]) /// 1-31 Not used pub struct InterruptMasterEnable: u16 { [0...
use util::{bitfields, bits::Bits, primitive_enum}; bitfields! { /// 4000208h - IME - Interrupt Master Enable Register (R/W) /// Bit Expl. /// 0 Disable all interrupts (0=Disable All, 1=See [`InterruptEnable`]) /// 1-31 Not used pub struct InterruptMasterEnable: u16 { [0...
Correct naming of master enable bit.
Correct naming of master enable bit.
Rust
mit
ExPixel/Pyrite2,ExPixel/Pyrite2
25430893c9d21b6ed1827aa48fef09d806c029b9
src/main.rs
src/main.rs
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; mod cli; fn main() { env_logger::init().expect("Failed to initialize logger."); run_cli(); } fn run_cli<'a>() -> Result<(), &'a str> { let matches = cli::app().get_matches(); let verbose_level = match matches.oc...
#[macro_use] extern crate clap; #[macro_use] extern crate log; extern crate env_logger; mod cli; use std::process::exit; fn main() { env_logger::init().expect("Failed to initialize logger."); match run_cli() { Ok(_) => {}, Err((message, exit_code)) => { error!("Error: {}", messag...
Add ability to exit non-zero if run_cli reports a failure
Add ability to exit non-zero if run_cli reports a failure
Rust
mit
jhelwig/homers
c27b2e299c624f6f53dc0e9935216c55f0a00006
examples/15_custom_validator.rs
examples/15_custom_validator.rs
use clap::{App, Arg}; fn main() { // You can define a function (or a closure) to use as a validator to argument values. The // function must accept a String and return Result<(), String> where Err(String) is the message // displayed to the user. let matches = App::new("myapp") // Application l...
use clap::{App, Arg}; fn main() { // You can define a function (or a closure) to use as a validator to argument values. The // function must accept a `&str` and return `Result<(), String>` where `Err(String)` is the // message displayed to the user. let matches = App::new("myapp") // Applicati...
Use correct type in comment
fix(example): Use correct type in comment Fixes #2631
Rust
apache-2.0
clap-rs/clap,clap-rs/clap,clap-rs/clap
8a7c1306b43895a97c0675c6d854afa468a22aad
src/test/ui/const-generics/parser-error-recovery/issue-89013.rs
src/test/ui/const-generics/parser-error-recovery/issue-89013.rs
trait Foo<const N: usize> { fn do_x(&self) -> [u8; N]; } struct Bar; const T: usize = 42; impl Foo<N = const 3> for Bar { //~^ERROR expected lifetime, type, or constant, found keyword `const` //~^^ERROR cannot constrain an associated constant to a value //~^^^ERROR this trait takes 1 generic argument but 0 gener...
trait Foo<const N: usize> { fn do_x(&self) -> [u8; N]; } struct Bar; const T: usize = 42; impl Foo<N = const 3> for Bar { //~^ ERROR expected lifetime, type, or constant, found keyword `const` //~| ERROR cannot constrain an associated constant to a value //~| ERROR this trait takes 1 generic argument but 0 gener...
Use less verbose syntax for error annotations
Use less verbose syntax for error annotations Co-authored-by: Esteban Kuber <5e12ad489afad14290b7861a616342b241775a66@users.noreply.github.com>
Rust
apache-2.0
graydon/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,graydon/rust
831ad549f9d0b5137bde66163c67352991c929f5
tests/features/mod.rs
tests/features/mod.rs
#[cfg(not(all( feature = "derive", feature = "full", feature = "parsing", feature = "printing", feature = "visit", feature = "visit-mut", feature = "fold", feature = "clone-impls", feature = "extra-traits", feature = "proc-macro", )))] mod error;
macro_rules! hide_from_rustfmt { ($($tt:tt)*) => { $($tt)* }; } #[cfg(not(all( feature = "derive", feature = "full", feature = "parsing", feature = "printing", feature = "visit", feature = "visit-mut", feature = "fold", feature = "clone-impls", feature = "extra-trait...
Hide the feature check parse error from rustfmt
Hide the feature check parse error from rustfmt
Rust
apache-2.0
dtolnay/syn
5c1f8924c479368956ede1acd8b7829d910b1b90
python/tidy/servo_tidy_tests/rust_tidy.rs
python/tidy/servo_tidy_tests/rust_tidy.rs
/* 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 app_units::Au; use azure::azure_hl::{AntialiasMode, Color, ColorPattern, CompositionOp}; use euclid::size::...
/* 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 app_units::Au; use azure::azure_hl::{AntialiasMode, Color, ColorPattern, CompositionOp}; use euclid::size::...
Tidy test for ignoring attributes
Tidy test for ignoring attributes
Rust
mpl-2.0
splav/servo,paulrouget/servo,canaltinova/servo,pyfisch/servo,fiji-flo/servo,canaltinova/servo,emilio/servo,pyfisch/servo,ConnorGBrewster/servo,mattnenterprise/servo,paulrouget/servo,peterjoel/servo,avadacatavra/servo,nnethercote/servo,dati91/servo,cbrewster/servo,anthgur/servo,DominoTree/servo,pyfisch/servo,nnethercote...
1b681d6652bacce6b741ca66725f25b9afb16bc8
src/test/ui/if-attrs/cfg-false-if-attr.rs
src/test/ui/if-attrs/cfg-false-if-attr.rs
// check-pass #[cfg(FALSE)] fn simple_attr() { #[attr] if true {} #[allow_warnings] if true {} } #[cfg(FALSE)] fn if_else_chain() { #[first_attr] if true { } else if false { } else { } } #[cfg(FALSE)] fn if_let() { #[attr] if let Some(_) = Some(true) {} } macro_rules! custom_macro { ...
// check-pass #[cfg(FALSE)] fn simple_attr() { #[attr] if true {} #[allow_warnings] if true {} } #[cfg(FALSE)] fn if_else_chain() { #[first_attr] if true { } else if false { } else { } } #[cfg(FALSE)] fn if_let() { #[attr] if let Some(_) = Some(true) {} } fn bar() { #[cfg(FALSE)] ...
Test that cfg-gated if-exprs are not type-checked
Test that cfg-gated if-exprs are not type-checked
Rust
apache-2.0
graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,graydon/rust
cf47daa8e140cf61e4d965df2840813a9d3fde8c
examples/todo/src/static_files.rs
examples/todo/src/static_files.rs
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() }
Return 404 on missing static file in todo example.
Return 404 on missing static file in todo example.
Rust
apache-2.0
shssoichiro/Rocket,antonpirker/Rocket,shssoichiro/Rocket,antonpirker/Rocket,antonpirker/Rocket,shssoichiro/Rocket
cff9a7dfadc6069bbc7b49c3ceb8497c78d426ab
crates/ra_hir/src/code_model_impl/konst.rs
crates/ra_hir/src/code_model_impl/konst.rs
use std::sync::Arc; use ra_syntax::ast::{NameOwner}; use crate::{ Name, AsName, Const, ConstSignature, Static, type_ref::{TypeRef}, PersistentHirDatabase, }; impl ConstSignature { pub(crate) fn const_signature_query( db: &impl PersistentHirDatabase, konst: Const, ) -...
use std::sync::Arc; use ra_syntax::ast::{self, NameOwner}; use crate::{ Name, AsName, Const, ConstSignature, Static, type_ref::{TypeRef}, PersistentHirDatabase, }; fn const_signature_for<N: NameOwner>( node: &N, type_ref: Option<&ast::TypeRef>, ) -> Arc<ConstSignature> { let nam...
Move ConstSignature creation to a single method
Move ConstSignature creation to a single method
Rust
apache-2.0
rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer
2deb98d76494fe657f8c870b926e159bcd307b87
libimagstore/src/lib.rs
libimagstore/src/lib.rs
#[macro_use] extern crate log; #[macro_use] extern crate version; extern crate fs2; extern crate glob; #[macro_use] extern crate lazy_static; extern crate regex; extern crate toml; #[cfg(test)] extern crate tempdir; extern crate semver; extern crate crossbeam; pub mod storeid; pub mod error; pub mod hook; pub mod stor...
#![deny( non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_mut, unused_qualifications, while_true, )] #[macro_use] extern crate log; #[macro_use] extern crate versi...
Add deny() so we turn some warnings into errors
Add deny() so we turn some warnings into errors
Rust
lgpl-2.1
matthiasbeyer/imag,mario-kr/imag,mario-kr/imag,matthiasbeyer/imag
2cbf17361ffb8415133b530184eb8607e22e3816
examples/metal_triangle.rs
examples/metal_triangle.rs
extern crate metl; use metl::extras::window::{Event, WindowBuilder}; use metl::{ClearColor, PixelFormat}; fn main() { let device = metl::Device::system_default_device().unwrap(); let mut window = WindowBuilder::new(device) .with_dimensions(800, 600) .with_title("Metal...
extern crate metl; use metl::extras::window::{Event, WindowBuilder, View, ViewDelegate}; use metl::{ClearColor, PixelFormat}; fn main() { struct MyViewDelegate; impl ViewDelegate for MyViewDelegate { fn draw_into_view(&self, view: &mut View) { view.draw(); } fn on_resize(&s...
Add a delegate to the example
Add a delegate to the example
Rust
apache-2.0
burtonageo/metl
0f24ccd21d9f734a21daaf3566900127167556d1
src/test/rustdoc/unit-return.rs
src/test/rustdoc/unit-return.rs
// aux-build:unit-return.rs #![crate_name = "foo"] extern crate unit_return; // @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone' pub fn f0<F: FnMut(u8) + Clone>(f: F) {} // @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone' pub fn f1<F: FnMut(u16) -> () + Clone>(f: F) {} // @...
// aux-build:unit-return.rs #![crate_name = "foo"] extern crate unit_return; // @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone' pub fn f0<F: FnMut(u8) + Clone>(f: F) {} // @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone' pub fn f1<F: FnMut(u16) -> () + Clone>(f: F) {} // @...
Change bound order in rustfmt test
Change bound order in rustfmt test It is unclear why this changed, but since it seems like a harmless change, we're going to move forward with reformatting.
Rust
apache-2.0
aidancully/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,graydon/rust,graydon/rust,aidancully/rust
77ae0e495ff13ef18bb7db607910022c6cca9c04
tests/lib.rs
tests/lib.rs
extern crate littletest; use littletest::{Runnable, TestResult, TestOptions, TestRunner}; struct TestCase { result: TestResult } unsafe impl Sync for TestCase {} impl TestCase { fn new(result: TestResult) -> TestCase { TestCase { result: result } } } impl Runnable for TestCa...
extern crate littletest; use littletest::{Runnable, TestResult, TestOptions, TestRunner}; struct TestCase { result: TestResult } impl TestCase { fn new(result: TestResult) -> TestCase { TestCase { result: result } } } impl Runnable for TestCase { fn run(&self) -> TestResu...
Remove an unneeded explicit Sync impl.
Remove an unneeded explicit Sync impl.
Rust
mit
justinlatimer/littletest
d410b80ab1372a185937af9adc09473691966bf3
Kata06/anagrams/src/lib.rs
Kata06/anagrams/src/lib.rs
use std::collections::HashMap; fn get_sorted_chars(string : &str) -> String { let mut chars : Vec<char> = string.chars().collect(); chars.sort(); let mut sorted_string = String::new(); for c in chars { sorted_string.push(c); } sorted_string } pub fn get_anagrams<'a>(strings : &[&'a str...
use std::collections::HashMap; fn get_sorted_chars(string : &str) -> String { let mut chars : Vec<char> = string.chars().collect(); chars.sort(); let mut sorted_string = String::new(); for c in chars { sorted_string.push(c); } sorted_string } pub fn get_anagrams<'a>(strings : &[&'a str...
Add simple test for anagram method
Kata06: Add simple test for anagram method
Rust
mit
SingingTree/CodeKata,SingingTree/CodeKata,SingingTree/CodeKata,SingingTree/CodeKata
d58946887e60576a3e42cf33b7397583dd3701a1
src/arch/x86_common/mod.rs
src/arch/x86_common/mod.rs
pub mod defs; pub mod barrier; pub mod memory;
use ::xen::StartInfo; pub mod defs; pub mod barrier; pub mod memory; extern { // Start info is not present on all architecture, this is why this // was made a global variable only for x86_* pub static start_info: *const StartInfo; }
Add definition of global start_info
x86_common: Add definition of global start_info
Rust
mit
uni-rs/uni.rs
96346761b5f0d34452f8c1178316bbfbe90f5b33
src/rot13.rs
src/rot13.rs
// Implements http://rosettacode.org/wiki/Rot-13 fn rot13 (string: &str) -> String { fn rot13u8 (c: char) -> char { let d = c as u8; match c { 'a' .. 'm' | 'A' .. 'M' => (d + 13) as char, 'n' .. 'z' | 'N' .. 'Z' => (d - 13) as char, _ => c...
// Implements http://rosettacode.org/wiki/Rot-13 fn rot13 (string: &str) -> String { fn rot13u8 (c: char) -> char { let d = c as u8; match c { 'a' .. 'm' | 'A' .. 'M' => (d + 13) as char, 'n' .. 'z' | 'N' .. 'Z' => (d - 13) as char, _ => c...
Remove unnecessary type annotation. `rustc` can figure it out itself.
Remove unnecessary type annotation. `rustc` can figure it out itself.
Rust
unlicense
crespyl/rust-rosetta,magum/rust-rosetta,pfalabella/rust-rosetta,crr0004/rust-rosetta,magum/rust-rosetta,JIghtuse/rust-rosetta,ZoomRmc/rust-rosetta,ghotiphud/rust-rosetta,Hoverbear/rust-rosetta,sakeven/rust-rosetta
957f11df3f613fa5bfbc0a96f353f8352391e60c
tests/fpe.rs
tests/fpe.rs
// 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)] exte...
// 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)] exte...
Rewrite the FPE test to not use Context directly
Rewrite the FPE test to not use Context directly
Rust
apache-2.0
QuiltOS/libfringe,whitequark/libfringe,QuiltOS/libfringe,whitequark/libfringe,RustOS-Fork-Holding-Ground/libfringe,RustOS-Fork-Holding-Ground/libfringe
bfcaf962d2bf6cebb09f79d26207cc15ee195a51
src/codecs.rs
src/codecs.rs
use ffi; use libc; use std::slice; use std::str; use std::ptr; use std::ffi::CStr; pub fn decode_c_str(c_str: *const ffi::yaml_char_t) -> Option<String> { if c_str == ptr::null() { None } else { unsafe { let i8_str = c_str as *const i8; str::from_utf8(CStr::from_ptr(i8...
use ffi; use libc; use std::slice; use std::str; use std::ptr; use std::ffi::CStr; use std::os::raw::c_char; pub fn decode_c_str(c_str: *const ffi::yaml_char_t) -> Option<String> { if c_str == ptr::null() { None } else { unsafe { let c_char_str = c_str as *const c_char; ...
Use c_char instead of i8 for ffi
Use c_char instead of i8 for ffi This allows the project to build on architectures which define c_char as u8. Fixes build problems in architectures provided by debian.
Rust
mit
kimhyunkang/libyaml-rust,kimhyunkang/libyaml-rust
abb0f2b5c43d94c32aa26a6f8936216584517707
tests/afl.rs
tests/afl.rs
// Regression tests from American Fuzzy Lop test cases. // 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 https://mozilla.org/MPL/2.0/. extern crate mp4parse; use std::io::Cursor; /// https://g...
// Regression tests from American Fuzzy Lop test cases. // 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 https://mozilla.org/MPL/2.0/. extern crate mp4parse; use std::io::Cursor; /// https://g...
Add regression test from fuzzing test cases.
Add regression test from fuzzing test cases. This is the test case from frewsxcv's fuzzing work, generated by American Fuzzy Lop's rust support. https://github.com/mozilla/mp4parse-rust/issues/4
Rust
mpl-2.0
mozilla/mp4parse-rust,kinetiknz/mp4parse-rust,kinetiknz/mp4parse-rust
3ab803845028b02e8c0174020c7ae2c6eb736f8f
tests/ui/crashes/auxiliary/proc_macro_crash.rs
tests/ui/crashes/auxiliary/proc_macro_crash.rs
// force-host // no-prefer-dynamic #![feature(repr128)] #![crate_type = "proc-macro"] extern crate proc_macro; use proc_macro::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; use std::iter::FromIterator; #[proc_macro] pub fn macro_test(input_stream: TokenStream) -> TokenStream { let first_token = input...
// no-prefer-dynamic // ^ compiletest by default builds all aux files as dylibs, but we don't want that for proc-macro // crates. If we don't set this, compiletest will override the `crate_type` attribute below and // compile this as dylib. Removing this then causes the test to fail because a `dylib` crate can't // con...
Remove force-host and explain no-prefer-dynamic
Remove force-host and explain no-prefer-dynamic
Rust
apache-2.0
graydon/rust,aidancully/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust
15bfe8a88ee8e2492c26c93fa6a7fa2093cd88a5
src/configuration.rs
src/configuration.rs
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()...
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()...
Use a plain map and avoid copying
Use a plain map and avoid copying
Rust
mit
schultyy/Sokan
cff755ccab5d883b3de1871cf6893fce632ae4f4
src/lib.rs
src/lib.rs
#[cfg(feature = "float")] extern crate num_traits; mod assertions; mod base; pub use assertions::basic::{ComparableAssertion, EqualityAssertion}; pub use assertions::float::FloatAssertion; pub use assertions::iterator::IteratorAssertion; pub use assertions::map::MapAssertion; pub use assertions::result::ResultAsserti...
#[cfg(feature = "float")] extern crate num_traits; mod assertions; mod base; pub use assertions::basic::{ComparableAssertion, EqualityAssertion}; #[cfg(feature = "float")] pub use assertions::float::FloatAssertion; pub use assertions::iterator::IteratorAssertion; pub use assertions::map::MapAssertion; pub use asserti...
Fix bug in float feature
Fix bug in float feature
Rust
apache-2.0
google/assertor
648824ecbe2dfe2aab30cd9190a3afc87786d76d
tests/test_client.rs
tests/test_client.rs
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(); ass...
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(); asser...
Use const instead of static for global constants
Use const instead of static for global constants
Rust
mit
messense/wechat-rs
cc557e16c3acb3c37b50abd93622221ca537d22d
tasks/animation/src/main.rs
tasks/animation/src/main.rs
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::...
#[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(...
Refactor to make the task look like the other gtk related tasks
Refactor to make the task look like the other gtk related tasks
Rust
unlicense
Hoverbear/rust-rosetta
49fb6260f30e4ad40fe6a7b83bed50dc8733a319
kudu-sys/src/lib.rs
kudu-sys/src/lib.rs
#[cfg(test)] mod test { #[test] fn it_works() { } }
#![allow(non_camel_case_types)] use std::os::raw::c_char; pub enum kudu_client_builder_t {} pub enum kudu_client_t {} pub enum kudu_status_t {} pub enum kudu_table_list_t {} extern "C" { //////////////////////////////////////////////////////////////////////////// // Kudu Status /////////////////////////...
Add initial Kudu FFI bindings
Add initial Kudu FFI bindings
Rust
apache-2.0
danburkert/kudu-rs
c73af486ddd5be2df0dd4c855886ad9b03103176
examples/commands/utility.rs
examples/commands/utility.rs
macro_rules! format_print ( ($format_str: expr, $opt_str: expr, $data: expr, $no_flag: expr) => ( { println!($format_str, if $no_flag { $opt_str } else { "" }, $data); } ); );
macro_rules! format_print ( ($format_str: expr, $opt_str: expr, $data: expr, $no_flag: expr) => ( { println!($format_str, if $no_flag { $opt_str } else { "" }, $data); } ); ); macro_rules! command ( ($name: ident) => ( { let args: $name::Arguments = Docopt::new...
Add macro for common command setup
Add macro for common command setup
Rust
bsd-3-clause
sourrust/flac
5709dd335031fec8a1105cad80f71f200af0fe2a
src/buffer/operation/mod.rs
src/buffer/operation/mod.rs
use buffer::Buffer; use buffer::gap_buffer::GapBuffer; pub use self::group::OperationGroup; pub mod group; pub trait Operation { fn run(&mut self, &mut GapBuffer); fn reverse(&mut self, &mut GapBuffer); }
use buffer::Buffer; use buffer::gap_buffer::GapBuffer; pub use self::group::OperationGroup; pub mod group; pub trait Operation { fn run(&mut self, &mut GapBuffer); fn reverse(&mut self, &mut GapBuffer); fn clone(&self) -> Box<Operation>; }
Add clone method to Operation trait.
Add clone method to Operation trait.
Rust
mit
jmacdonald/scribe
f4f7bb232e49ec4b671d4ba18a516b45ea6c5e15
tests/smoke.rs
tests/smoke.rs
extern crate futures; extern crate tokio_core; extern crate tokio_process; use std::env; use std::sync::mpsc::channel; use std::sync::{Once, ONCE_INIT}; use std::thread; use tokio_core::{Loop, LoopHandle}; use tokio_process::Command; static INIT: Once = ONCE_INIT; fn init() { INIT.call_once(|| { let (tx...
extern crate futures; extern crate tokio_core; extern crate tokio_process; use std::env; use std::sync::mpsc::channel; use std::sync::{Once, ONCE_INIT}; use std::thread; use tokio_core::{Loop, LoopHandle}; use tokio_process::Command; static INIT: Once = ONCE_INIT; fn init() { INIT.call_once(|| { let (tx...
Fix a test on Windows
process: Fix a test on Windows
Rust
mit
tokio-rs/tokio,tokio-rs/tokio
383fb14f33927f0198a463277e9f7458df4bf2ea
mockall/tests/automock_constructor_in_struct.rs
mockall/tests/automock_constructor_in_struct.rs
// vim: tw=80 //! A struct with a constructor method #![deny(warnings)] use mockall::*; pub struct A {} #[automock] impl A { pub fn new() -> Self { unimplemented!() } } #[test] fn returning() { let ctx = MockA::new_context(); ctx.expect().returning(MockA::default); let _a: MockA = MockA:...
// vim: tw=80 //! A struct with a constructor method #![deny(warnings)] use mockall::*; pub struct A {} #[automock] #[allow(clippy::new_without_default)] impl A { pub fn new() -> Self { unimplemented!() } } #[test] fn returning() { let ctx = MockA::new_context(); ctx.expect().returning(MockA...
Fix a Clippy lint on the latest nightly
Fix a Clippy lint on the latest nightly
Rust
apache-2.0
asomers/mockall,asomers/mockall
1e75543481635df8d9fe676c4723f8d37dee53fd
src/vector.rs
src/vector.rs
//! Define trait for vectors use ndarray::{LinalgScalar, Array, Ix1}; use num_traits::float::Float; /// Methods for vectors pub trait Vector { type Scalar; /// L-2 norm fn norm(&self) -> Self::Scalar; } impl<A: Float + LinalgScalar> Vector for Array<A, Ix1> { type Scalar = A; fn norm(&self) -> Se...
//! Define trait for vectors use ndarray::{NdFloat, Array, RcArray, Ix1}; /// Methods for vectors pub trait Vector { type Scalar; /// L-2 norm fn norm(&self) -> Self::Scalar; } impl<A: NdFloat> Vector for Array<A, Ix1> { type Scalar = A; fn norm(&self) -> Self::Scalar { self.dot(&self).sq...
Implement Vector for RcArray<NdFloat, Ix1>
Implement Vector for RcArray<NdFloat, Ix1>
Rust
mit
termoshtt/ndarray-linalg
4cae3f8c4182e79726f7dbef25e3c13b0fff7d12
src/commands/react_native.rs
src/commands/react_native.rs
use clap::{App, ArgMatches}; use prelude::*; use config::Config; use commands::{react_native_xcode, react_native_gradle, react_native_codepush}; pub fn make_app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> { app.about("provides helpers for react-native.") .subcommand(react_native_xcode::make_app(App::ne...
use clap::{App, ArgMatches}; use prelude::*; use config::Config; use commands; macro_rules! each_subcommand { ($mac:ident) => { $mac!(react_native_gradle); $mac!(react_native_codepush); #[cfg(target_os="macos")] $mac!(react_native_xcode); } } pub fn make_app<'a, 'b: 'a>(mut a...
Make sure react-native xcode does not compile on non osx
Make sure react-native xcode does not compile on non osx
Rust
bsd-3-clause
getsentry/sentry-cli,getsentry/sentry-cli,getsentry/sentry-cli
613d4f937598cedecb2242a22c6d81355902ec11
enum-map/src/arbitrary.rs
enum-map/src/arbitrary.rs
use crate::internal::Array; use crate::{enum_map, Enum, EnumMap}; use arbitrary::{Arbitrary, Result, Unstructured}; impl<'a, K: Enum<V>, V: Arbitrary<'a>> Arbitrary<'a> for EnumMap<K, V> { fn arbitrary(u: &mut Unstructured<'a>) -> Result<EnumMap<K, V>> { Ok(enum_map! { _ => Arbitrary::arbitrary...
use crate::internal::Array; use crate::{enum_map, Enum, EnumMap}; use arbitrary::{Arbitrary, Result, Unstructured}; /// Requires crate feature `"serde"` impl<'a, K: Enum<V>, V: Arbitrary<'a>> Arbitrary<'a> for EnumMap<K, V> { fn arbitrary(u: &mut Unstructured<'a>) -> Result<EnumMap<K, V>> { Ok(enum_map! { ...
Document that Arbitrary implementation requires crate feature
Document that Arbitrary implementation requires crate feature
Rust
apache-2.0
xfix/enum-map
19322b667adaefb600ff71d46aa794ca7059190e
libimaglink/src/internal.rs
libimaglink/src/internal.rs
use libimagstore::store::EntryHeader; use error::{LinkError, LinkErrorKind}; use link::{Link, Links}; use result::Result; use toml::Value; pub fn get_links(header: &EntryHeader) -> Result<Links> { process_rw_result(header.read("imag.links")) } /// Set the links in a header and return the old links, if any. pub ...
use libimagstore::store::EntryHeader; use libimagstore::store::Result as StoreResult; use error::{LinkError, LinkErrorKind}; use link::{Link, Links}; use result::Result; use toml::Value; pub fn get_links(header: &EntryHeader) -> Result<Links> { process_rw_result(header.read("imag.links")) } /// Set the links in...
Add helper for processing store result
Add helper for processing store result
Rust
lgpl-2.1
matthiasbeyer/imag,mario-kr/imag,mario-kr/imag,matthiasbeyer/imag
169946a892533a6e907ae66dbb62fbe5a52bc47f
src/lib.rs
src/lib.rs
// This file is part of Genesis. // Genesis is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Genesis is distributed in th...
// This file is part of Genesis. // Genesis is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Genesis is distributed in th...
Update to new unstable feature names
cfg: Update to new unstable feature names The "core" feature was split into multiple features.
Rust
agpl-3.0
dschatzberg/genesis,dschatzberg/genesis
2acdacf6808c8d59448c69ae729d45fe8d8863aa
rust/src/main.rs
rust/src/main.rs
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\...
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 reade...
Use num_seqs == 1 to decide if min and max need initialisation
Use num_seqs == 1 to decide if min and max need initialisation
Rust
mit
bjpop/biotool,supernifty/biotool,supernifty/biotool,bjpop/biotool,drpowell/biotool,lonsbio/biotool,biotool-paper/biotool,drpowell/biotool,drpowell/biotool,biotool-paper/biotool,supernifty/biotool,supernifty/biotool,supernifty/biotool,biotool-paper/biotool,drpowell/biotool,drpowell/biotool,biotool-paper/biotool,drpowell...
6d3e9410759042880aefd4ced5866261ad2a7022
src/main.rs
src/main.rs
extern crate hyper; extern crate rustc_serialize; use rustc_serialize::json; mod state; use hyper::server::{Server, Request, Response}; fn hello(req: Request, res: Response) { let game = state::initialState(); let encoded = json::encode(&game).unwrap(); res.send(encoded.as_bytes()).unwrap(); } fn main() { ...
extern crate hyper; extern crate rustc_serialize; mod state; use rustc_serialize::json; use hyper::Get; use hyper::server::{Server, Request, Response}; use hyper::uri::RequestUri::AbsolutePath; macro_rules! try_return( ($e:expr) => {{ match $e { Ok(v) => v, Err(e) => { println!("Error: {...
Handle each http request based on it's path and method
Handle each http request based on it's path and method
Rust
mit
d3k4r/aqueren
bcd6fe35e0b7577de7a72114270f9c2daa431738
src/test/rustdoc/intra-link-prim-precedence.rs
src/test/rustdoc/intra-link-prim-precedence.rs
// ignore-tidy-linelength #![deny(broken_intra_doc_links)] pub mod char {} /// See also [type@char] // @has intra_link_prim_precedence/struct.MyString.html '//a/@href' 'https://doc.rust-lang.org/nightly/std/primitive.char.html' pub struct MyString; /// See also [char] // @has intra_link_prim_precedence/struct.MyStri...
// ignore-tidy-linelength #![deny(broken_intra_doc_links)] pub mod char { /// [char] // @has intra_link_prim_precedence/char/struct.Inner.html '//a/@href' 'https://doc.rust-lang.org/nightly/std/primitive.char.html' pub struct Inner; } /// See [prim@char] // @has intra_link_prim_precedence/struct.MyString....
Update primitive test to match the new behavior
Update primitive test to match the new behavior
Rust
apache-2.0
graydon/rust,aidancully/rust,aidancully/rust,aidancully/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,graydon/rust,graydon/rust
e89ad9c7544e36ac0667d86d6643dce5dd05401a
compiler/crates/fixture-tests/src/print_diff.rs
compiler/crates/fixture-tests/src/print_diff.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use colored::Colorize; use diff::Result::*; /// Prints a diff between the expected and actual strings to stdout. pub(crate) fn pri...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use colored::Colorize; use diff::Result::*; /// Prints a diff between the expected and actual strings to stdout. pub(crate) fn pri...
Fix clippy errors in fixture-tests
Fix clippy errors in fixture-tests Reviewed By: tyao1 Differential Revision: D26773119 fbshipit-source-id: 650f2e7852ddd26a1ff0d2807de05f639d233ffd
Rust
mit
wincent/relay,xuorig/relay,yungsters/relay,wincent/relay,facebook/relay,yungsters/relay,kassens/relay,facebook/relay,xuorig/relay,josephsavona/relay,facebook/relay,kassens/relay,xuorig/relay,atxwebs/relay,kassens/relay,wincent/relay,kassens/relay,atxwebs/relay,xuorig/relay,josephsavona/relay,wincent/relay,xuorig/relay,...
03074c0ef71485f75c8d69f877960311304be15f
src/phi.rs
src/phi.rs
use value::Value; use block::BasicBlock; use ffi::core; /// A PHI node represents a value which is selected based on the predecessor of the current block. pub type PhiNode = Value; impl PhiNode { /// Adds an incoming value to the end of this PHI node. pub fn add_incoming(&self, val: &Value, block: &BasicBlock) { ...
use std::mem; use std::ops::Deref; use std::ptr; use ffi::core; use ffi::prelude::LLVMValueRef; use block::BasicBlock; use value::Value; use util::CastFrom; /// A PHI node represents a value which is selected based on the predecessor of the current block. pub struct PhiNode; native_ref!(&PhiNode = LLVMValueRef); i...
Make PHI nodes more type safe.
Make PHI nodes more type safe.
Rust
bsd-3-clause
hyunsik/llvm-rust
8fc3ef130a4587e96b4319db801984d2997f9077
tests/compile-fail/extern.rs
tests/compile-fail/extern.rs
#![feature(plugin)] #![plugin(tag_safe)] // Path is relative to rustc invocation directory - package root in this case #[tagged_safe(print="tests/compile-fail/libstd_foo.txt")] extern crate std as _std; #[req_safe(print)] #[deny(not_tagged_safe)] fn main() { bar(); //~^ ERROR Calling print-unsafe method from } ...
#![feature(plugin)] #![plugin(tag_safe)] // Path is relative to rustc invocation directory - package root in this case #[allow(unused_extern_crates)] #[tagged_safe(print="tests/compile-fail/libstd_foo.txt")] extern crate std as _std; #[req_safe(print)] #[deny(not_tagged_safe)] fn main() { bar(); //~^ ERROR Calli...
Fix compile-fail test which had a new warning
Fix compile-fail test which had a new warning
Rust
mit
thepowersgang/tag_safe
35c49af9cc0701bbc8bd1d8ccdc41855125854e5
src/bin/boot-delay.rs
src/bin/boot-delay.rs
use std::fs::File; use std::io::Read; use std::mem::transmute; use std::thread::sleep_ms; use std::env; fn main() { let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) { Some(d) => 60.0 * d, None => { println!("Usage: boot-delay <minutes>"); return; ...
use std::fs::File; use std::io::Read; use std::mem::transmute; use std::thread::sleep; use std::env; use std::time::Duration; fn main() { let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) { Some(d) => 60.0 * d, None => { println!("Usage: boot-delay <minutes>"); ...
Fix deprecated sleep_ms(u32) warning, use sleep(Duration)
Fix deprecated sleep_ms(u32) warning, use sleep(Duration)
Rust
mit
systemd-cron/systemd-cron-next,systemd-cron/systemd-cron-next
c34c77c764491460449a6bef06b2149c3ab82f2d
src/test/debuginfo/function-arguments-naked.rs
src/test/debuginfo/function-arguments-naked.rs
// min-lldb-version: 310 // We have to ignore android because of this issue: // https://github.com/rust-lang/rust/issues/74847 // ignore-android // // We need to use inline assembly, so just use one platform // only-x86_64 // compile-flags:-g // === GDB TESTS =========================================================...
// min-lldb-version: 310 // We have to ignore android because of this issue: // https://github.com/rust-lang/rust/issues/74847 // ignore-android // // We need to use inline assembly, so just use one platform // only-x86_64 // compile-flags:-g // === GDB TESTS =========================================================...
Apply `extern "C"` calling convention
Apply `extern "C"` calling convention Co-authored-by: Amanieu d'Antras <92db609b8007e8ad5e633f1530d9df21d90665f4@gmail.com>
Rust
apache-2.0
aidancully/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,graydon/rust,aidancully/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,graydon/rust
dc8d29be4ac405e61b6c403b0ea09809e55b8efa
tests/run-pass/ice_exacte_size.rs
tests/run-pass/ice_exacte_size.rs
#![deny(clippy)] #[allow(dead_code)] struct Foo; impl Iterator for Foo { type Item = (); fn next(&mut self) -> Option<()> { let _ = self.len() == 0; unimplemented!() } } impl ExactSizeIterator for Foo {} fn main() {}
#![deny(clippy)] #[allow(dead_code)] struct Foo; impl Iterator for Foo { type Item = (); #[allow(unimplemented)] fn next(&mut self) -> Option<()> { let _ = self.len() == 0; unimplemented!() } } impl ExactSizeIterator for Foo {} fn main() {}
Allow unimplemented in other tests
Allow unimplemented in other tests
Rust
apache-2.0
aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,aidancully/rust,graydon/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,graydon/rust
4385ddf842f7b4d0219264972a71362b59cf4605
src/lib.rs
src/lib.rs
#[deny(missing_docs)] extern crate bosun_emitter; #[macro_use] extern crate chan; extern crate chan_signal; #[macro_use] extern crate log; extern crate env_logger; extern crate rustc_serialize; extern crate toml; pub mod config;
#[deny(missing_docs)] extern crate bosun_emitter; #[macro_use] extern crate chan; extern crate chan_signal; #[macro_use] extern crate log; extern crate env_logger; extern crate rustc_serialize; extern crate toml; pub mod bosun; pub mod collectors; pub mod config; pub mod scheduler;
Add all mods to compilation
Add all mods to compilation
Rust
mit
lukaspustina/rs-collector,lukaspustina/rs-collector
fb2c51c0393bb41b453869425014de38f4d18591
src/lib.rs
src/lib.rs
//! 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 { ...
Add a unit test to ensure that ctypes are imported
Add a unit test to ensure that ctypes are imported Signed-off-by: Cruz Julian Bishop <2ec049a14d87a31aea1a3d03a4724ab112720c17@gmail.com>
Rust
mit
Techern/linux-api-rs
13e009099651dd12c0bd5521672fcea74f3c793f
scratchapixel/src/geometry/vector.rs
scratchapixel/src/geometry/vector.rs
use std::ops::{Mul,Add}; #[derive(Copy,Clone)] pub struct Vec3<T: Mul<T, Output = T> + Add<T, Output = T> + Copy + Clone> { x: T, y: T, z: T, } impl <T: Mul<T, Output = T> + Add<T, Output = T> + Copy + Clone> Vec3<T> { pub fn norm(self) -> T { (self.x * self.x + self.y * self.y + self.z * self...
use std::ops::{Mul,Add}; pub struct Vec3<T: Mul<T, Output = T> + Add<T, Output = T> + Copy + Clone> { x: T, y: T, z: T, } impl <T: Mul<T, Output = T> + Add<T, Output = T> + Copy + Clone> Vec3<T> { pub fn norm(self) -> T { (self.x * self.x + self.y * self.y + self.z * self.z) } } #[cfg(tes...
Remove Copy and Clone trait from Vec3
Remove Copy and Clone trait from Vec3 These traits are not necessary to make norm work. Only the type of the Vec3 fields should implement Copy and Clone traits.
Rust
mit
Chair-of-Indefinite-Studies/scratchapixel
87241e909933b30bb31af4edf58d1a331589df3c
src/test/ui/deriving/issue-89188-gat-hrtb.rs
src/test/ui/deriving/issue-89188-gat-hrtb.rs
// check-pass #![feature(generic_associated_types)] trait CallWithShim: Sized { type Shim<'s> where Self: 's; } #[derive(Clone)] struct ShimMethod<T: CallWithShim + 'static>(pub &'static dyn for<'s> Fn(&'s mut T::Shim<'s>)); trait CallWithShim2: Sized { type Shim<T>; } struct S<'s>(&'s ()); #[...
// check-pass #![feature(generic_associated_types)] trait CallWithShim: Sized { type Shim<'s> where Self: 's; } #[derive(Clone)] struct ShimMethod<T: CallWithShim + 'static>(pub &'static dyn for<'s> Fn(&'s mut T::Shim<'s>)); trait CallWithShim2: Sized { type Shim<T>; } struct S<'s>(&'s ()); #[...
Expand one test (from jackh726)
Expand one test (from jackh726)
Rust
apache-2.0
graydon/rust,aidancully/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,graydon/rust,aidancully/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust
46465e2dcd0ed4c0400b2fbc40b3829d878ea467
src/main.rs
src/main.rs
use std::thread; use std::sync::Mutex; struct Philosopher { name: String } impl Philosopher { fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string() } } fn eat(&self) { println!("{} is eating.", self.name); thread::sleep_ms(1000); ...
use std::thread; use std::sync::Mutex; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, }...
Add `left` and `right` fields to `Philosopher`
Add `left` and `right` fields to `Philosopher`
Rust
mit
juliangrosshauser/dining_philosophers
cc42f2e661eddef90290ba073af4110ee6074b9e
rust/test/derive/clone_dyn_tests.rs
rust/test/derive/clone_dyn_tests.rs
#[ allow( unused_imports ) ] use clone_dyn as TheModule; #[ allow( unused_imports ) ] use test_tools::*; mod clone_dyn_test;
#[ allow( unused_imports ) ] use clone_dyn as TheModule; #[ allow( unused_imports ) ] use test_tools::*; #[ cfg( any( feature = "use_std", feature = "use_alloc" ) ) ] mod clone_dyn_test;
Fix tests of module `clone_dyn`, test code under features
Fix tests of module `clone_dyn`, test code under features
Rust
mit
Wandalen/wTools,Wandalen/wTools
d6abf189b87877d6a54284825fb9efb066cd42b7
src/peruse/lib.rs
src/peruse/lib.rs
#![feature(globs)] #![feature(phase)] #![feature(unboxed_closures)] #![feature(macro_rules)] extern crate regex; pub mod parsers; #[macro_escape] pub mod macros; mod tests; mod peruse { pub use parsers; }
#![feature(unboxed_closures)] extern crate regex; pub mod parsers; #[macro_use] pub mod macros; mod tests; mod peruse { pub use parsers; }
Update crate/module attributes for newer Rust
Update crate/module attributes for newer Rust
Rust
mit
DanSimon/peruse
93cd82056c709f3cb9e52b8e2860109d72e58df9
rust/test/iter/basic_test.rs
rust/test/iter/basic_test.rs
use super::TheModule; use TheModule::*; use test_tools::*; // fn basic_test() { // test.case( "basic" ); let src = vec![ 1, 2, 3 ]; let exp = ( vec![ 2, 3, 4 ], vec![ 0, 1, 2 ] ); let got : ( Vec< _ >, Vec< _ > ) = src.iter().map( | e | {( e + 1, e - 1, )}).multiunzip(); assert_eq!( got, exp ); ...
use super::TheModule; use TheModule::*; use test_tools::*; // tests_impls! { #[ test ] fn basic() { // test.case( "basic" ); let src = vec![ 1, 2, 3 ]; let exp = ( vec![ 2, 3, 4 ], vec![ 0, 1, 2 ] ); let got : ( Vec< _ >, Vec< _ > ) = src.iter().map( | e | {( e + 1, e - 1, )}...
Update tests of module `iter_tools`, use new test macroses
Update tests of module `iter_tools`, use new test macroses
Rust
mit
Wandalen/wTools,Wandalen/wTools
ac124dc448e00b166daf296bc79f582857a4e319
src/metadata/parser.rs
src/metadata/parser.rs
use nom::be_u8; use utility::to_u32; named!(header <&[u8], (u8, bool, u32)>, chain!( block_byte: be_u8 ~ length: map!(take!(3), to_u32), || { let is_last = (block_byte >> 7) == 1; let block_type = block_byte & 0b01111111; (block_type, is_last, length) } ) );
use nom::{ be_u8, IResult, ErrorCode, Err, }; use metadata::BlockData; use utility::to_u32; named!(header <&[u8], (u8, bool, u32)>, chain!( block_byte: be_u8 ~ length: map!(take!(3), to_u32), || { let is_last = (block_byte >> 7) == 1; let block_type = block_byte & 0b01111111; ...
Add general function to parse all block types
Add general function to parse all block types
Rust
bsd-3-clause
sourrust/flac
95e25cf787a806eec12a672dd554a0bb612b9315
tests/test_repr.rs
tests/test_repr.rs
mod drop; use self::drop::DetectDrop; use anyhow::Error; use std::marker::Unpin; use std::mem; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; #[test] fn test_error_size() { assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>()); } #[test] fn test_autotraits(...
mod drop; use self::drop::DetectDrop; use anyhow::Error; use std::marker::Unpin; use std::mem; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; #[test] fn test_error_size() { assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>()); } #[test] fn test_null_pointe...
Test null pointer optimization of Result<(), Error>
Test null pointer optimization of Result<(), Error>
Rust
apache-2.0
dtolnay/anyhow
1bfdb804b27ebb9ecde4ac9d638c034a446767f0
traits/src/lib.rs
traits/src/lib.rs
pub trait Summarizable { fn summary(&self) -> String { String::from("Read more...") } } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summarizable for NewsArticle { fn summary(&self) -> String { format!(...
pub trait Summarizable { fn author_summary(&self) -> String; fn summary(&self) -> String { String::from("Read more from {}...", self.author_summary()) } } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } impl Summariza...
Change default implementation so it uses other method defined in trait
Change default implementation so it uses other method defined in trait
Rust
mit
pgrzesik/learning-rust
80fb80c9111af6eee5c1996c3bf520c4e92693b9
src/utils.rs
src/utils.rs
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com> // // 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 ap...
Fix missing_docs warning when builting without TLS
Fix missing_docs warning when builting without TLS
Rust
apache-2.0
dtantsur/rust-openstack,dtantsur/rust-openstack
6fb721fd7b82262bacfc077dcab66b02e14d8282
src/write.rs
src/write.rs
use {SChunks}; use std::io::Error; use std::fs::File; use std::io::Write; /// This function takes as parameter a file name and a vector of chaunks. /// The function will create a file, and append to the buffer each chunk. pub fn write_file(name_file: &str, chunks: &SChunks) -> Result<(), Error> { // Create th...
use {SChunks}; use std::io::Error; use std::fs::File; use std::io::Write; /// This function takes as parameter a file name and a vector of chaunks. /// The function will create a file, and append to the buffer each chunk. pub fn write_file(local_file: &mut File, chunks: &SChunks) -> Result<(), Error> { // Get the...
Change the definition of the function
Change the definition of the function
Rust
mit
derniercri/snatch
e29d5b8858ae12f4ddf8a3b1d04fc631fc1ddec1
src/iota/lib.rs
src/iota/lib.rs
//! 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(st...
//! 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")] e...
Move back to stable rust
Move back to stable rust
Rust
mit
gchp/iota
3bfb15ba5cb500f84193ea17f73bcca68b060f53
tests/cli.rs
tests/cli.rs
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"));...
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"));...
Update check target with current expected localization
test(i18n): Update check target with current expected localization
Rust
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
fb5c4b6fc5e76765004967eba0fd4ce5a3833058
rust/test/commandsaggregator/commandsaggregator.rs
rust/test/commandsaggregator/commandsaggregator.rs
#[test] fn full_interface() { }
use std::collections::HashMap; /* var track = []; var commandWith = ( e ) => { track.push( 'with' ) }; var Commands = { 'with' : { ro : commandWith, h : 'with', lh : 'WITH' }, }; var aggregator = _.CommandsAggregator ({ commands : Commands, }).form(); aggregator.instructionPerform({ command...
Write example with full interface
Write example with full interface
Rust
mit
Wandalen/wTools,Wandalen/wTools
7ddeb0f4b57d263b19670e4e3420ad2ef2c87878
src/setup/mod.rs
src/setup/mod.rs
use git2::Repository; use std::{error, fs, io, path, result}; type Result<T> = result::Result<T, Box<dyn error::Error>>; /// Setup CaSILE config file(s) on new repository pub fn run(path: path::PathBuf) -> Result<()> { crate::header("setup-header"); let metadata = fs::metadata(&path)?; match metadata.is_d...
use crate::i18n::LocalText; use git2::Repository; use std::{error, fs, io, path, result}; type Result<T> = result::Result<T, Box<dyn error::Error>>; /// Setup CaSILE config file(s) on new repository pub fn run(path: path::PathBuf) -> Result<()> { crate::header("setup-header"); let metadata = fs::metadata(&pat...
Use new LocalText interface for error messages
chore(i18n): Use new LocalText interface for error messages
Rust
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
6a21170217cdea88bd0445788a59834cb2a5f20a
src/common.rs
src/common.rs
pub enum ASN1Tag { Bool = 1, Integer = 2, BitString = 3, OctetString = 4, ObjectIdentifier = 6, PrintableString = 19, UTCTime = 23, Sequence = 48, }
const ASN1_CONSTRUCTED_FLAG: isize = 0x20; pub enum ASN1Tag { Bool = 0x1, Integer = 0x2, BitString = 0x3, OctetString = 0x4, ObjectIdentifier = 0x6, PrintableString = 0x13, UTCTime = 0x17, Sequence = (0x10 | ASN1_CONSTRUCTED_FLAG), }
Use hex and show your work in the ASN1Tag enum
Use hex and show your work in the ASN1Tag enum
Rust
bsd-3-clause
alex/rust-asn1,alex/rust-asn1
db321f0f0301671a0dc68e4e2d9a4cc00781f8a1
tests/error_handler.rs
tests/error_handler.rs
use std::error::Error; use std::thread; use ::arrayfire::*; macro_rules! implement_handler { ($fn_name:ident) => { pub fn $fn_name(error_code: AfError) { match error_code { AfError::SUCCESS => {} /* No-op */ _ => panic!("Error message: {}", error_code), ...
use std::thread; use ::arrayfire::*; macro_rules! implement_handler { ($fn_name:ident) => { pub fn $fn_name(error_code: AfError) { match error_code { AfError::SUCCESS => {} /* No-op */ _ => panic!("Error message: {}", error_code), } } }; ...
Fix unused import warning in error handler test
Fix unused import warning in error handler test
Rust
bsd-3-clause
9prady9/arrayfire-rust,arrayfire/arrayfire-rust,arrayfire/arrayfire_rust,9prady9/arrayfire-rust,arrayfire/arrayfire-rust,arrayfire/arrayfire-rust,9prady9/arrayfire-rust,9prady9/arrayfire-rust
39c2e0b773aab43bdc8b6b5f73e2b90d2ae562c7
24_iterators/src/lib.rs
24_iterators/src/lib.rs
struct Counter { count: u32 } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.count) } else { ...
struct Counter { count: u32 } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count < 6 { Some(self.count) } else { ...
Implement test for counter iterator
Implement test for counter iterator
Rust
mit
pgrzesik/learning-rust
a740f7677211ffdcf293e98984d7a7ddb5b4f9b8
test_suite/no_std/src/main.rs
test_suite/no_std/src/main.rs
// Copyright 2017 Serde Developers // // 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 accordin...
// Copyright 2017 Serde Developers // // 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 accordin...
Update no-std panic signature for nightly-2018-06-03
Update no-std panic signature for nightly-2018-06-03
Rust
apache-2.0
serde-rs/serde
2a029261551634d95a991b5b3d6265d6438088a9
src/download/src/errors.rs
src/download/src/errors.rs
error_chain! { links { } foreign_links { Io(::std::io::Error) #[cfg(unix)]; } errors { HttpStatus(e: u32) { description("http request returned an unsuccessful status code") display("http request returned an unsuccessful status code: {}", e) } F...
error_chain! { links { } foreign_links { Io(::std::io::Error); } errors { HttpStatus(e: u32) { description("http request returned an unsuccessful status code") display("http request returned an unsuccessful status code: {}", e) } FileNotFound {...
Remove unix-only flag on std::io::Error error_chain foreign link
Remove unix-only flag on std::io::Error error_chain foreign link I don't know why I put it there in the first place
Rust
apache-2.0
theindigamer/rustup.rs,inejge/rustup.rs,rust-lang/rustup,inejge/rustup.rs,Boddlnagg/rustup.rs,rust-lang/rustup,Boddlnagg/rustup.rs,rust-lang/rustup,nodakai/rustup.rs,Boddlnagg/rustup.rs,nodakai/rustup.rs,inejge/rustup.rs,theindigamer/rustup.rs,Boddlnagg/rustup.rs,rust-lang/rustup,theindigamer/rustup.rs,nodakai/rustup.r...
f35848c4eabd101be967a5a75741a00de62516b9
src/lib.rs
src/lib.rs
#[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()...
#[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()...
Remove needless lifetimes in create_post signature
Remove needless lifetimes in create_post signature
Rust
apache-2.0
diesel-rs/diesel,sgrif/diesel,sgrif/diesel,diesel-rs/diesel
dd895329570038ed901f05e1dc961c073641ba6d
filesystem/apps/sodium/exec.rs
filesystem/apps/sodium/exec.rs
use super::*; use redox::*; impl Editor { pub fn exec(&mut self, Inst(n, cmd): Inst) { use super::Mode::*; use super::PrimitiveMode::*; use super::CommandMode::*; match self.cursor().mode { Command(Normal) => match cmd { 'i' => { self....
use super::*; use redox::*; impl Editor { pub fn exec(&mut self, Inst(n, cmd): Inst) { use super::Mode::*; use super::PrimitiveMode::*; use super::CommandMode::*; match self.cursor().mode { Command(Normal) => match cmd { 'i' => { self....
Add $ and 0 commands
Add $ and 0 commands
Rust
mit
bheesham/redox,imp/redox,nounoursheureux/redox,skylerberg/redox,NobbZ/redox,fischmax/redox,fischmax/redox,bheesham/redox,stryan/redox,nounoursheureux/redox,LazyOxen/redox,tedsta/redox,NobbZ/redox,stryan/redox,esell/redox,fischmax/redox,vvlevchenko/redox,vvlevchenko/redox,nounoursheureux/redox,skylerberg/redox,tedsta/re...
a3ab3e739095a17074169d4a697baa34edf5432d
src/persist.rs
src/persist.rs
trait Persister { fn add_item(&self, &Item) -> i32; fn change_item_desc(&self, i32, &str); fn update_item(&self, &Item); fn remove_item(&self, i32); fn get_items(&self) -> Vec<Item>; }
trait Persister { fn add_item(&self, desc: &str) -> i32; fn change_item_desc(&self, id: i32, desc: &str) -> Result<(), ()>; fn update_item(&self, id: i32, last_reviewed: i32, ff: f64, int_step: i32, iri: f64) -> Result<(), ()>; fn remove_item(&self, id: i32) -> Result<(), ()>; fn get_items(&self) ->...
Rework params of Persister trait methods
Rework params of Persister trait methods
Rust
apache-2.0
nham/hippo
ca253f70ff62929e3fc8742ea54253907d5277c7
examples/file_chooser.rs
examples/file_chooser.rs
extern crate file_dialog; extern crate glfw_window; extern crate shader_version; extern crate opengl_graphics; use file_dialog::FileDialog; use glfw_window::GlfwWindow; use opengl_graphics::glyph_cache::GlyphCache as Font; use shader_version::opengl::OpenGL; fn main() { let font = Font::new(&Path::new("./assets/D...
extern crate file_dialog; extern crate glfw_window; extern crate shader_version; extern crate opengl_graphics; use file_dialog::FileDialog; use glfw_window::GlfwWindow; use opengl_graphics::glyph_cache::GlyphCache as Font; use shader_version::opengl::OpenGL; use std::io::fs::PathExtensions; fn main() { let font ...
Print selected file in test
Print selected file in test
Rust
mit
cybergeek94/file_dialog
3b60bcca8c6489c458a2a96072ffc9a7a05f4c3a
shared/tests/rsi.rs
shared/tests/rsi.rs
extern crate shared; extern crate image; use image::{open, GenericImage}; use shared::rsi::Rsi; use std::path::Path; use std::env; #[test] fn testrsi() { let path = Path::new("tests/data/testrsi.rs.rsi"); println!("{:?}", env::current_dir()); assert!(path.is_dir()); let rsi = Rsi::open(path).unwrap(...
extern crate shared; extern crate image; use image::{open, GenericImage}; use shared::rsi::Rsi; use std::path::Path; #[test] fn test_extract() { let path = Path::new("tests/data/testrsi.rs.rsi"); let rsi = Rsi::open(path).unwrap(); let otherbyethere = open("tests/data/testrsi.rs_byethere_3.png").unwrap();...
Add another unit test because why not.
Add another unit test because why not.
Rust
agpl-3.0
NanotrasenInc/YASSS13RTWCF
f151b399d960a2ed24daf59e00a62f678757b906
base/src/lib.rs
base/src/lib.rs
extern crate num_traits; #[macro_use] extern crate log; pub mod math; pub mod world;
//! Functionality used by both the plantex server and the plantex client. //! //! - the `math` module reexports everything from the `cgmath` crate and //! defines a few own type //! - the world module is all about saving and managing the game world //! extern crate num_traits; #[macro_use] extern crate log; pub mod ...
Add a short root module documentation
Add a short root module documentation
Rust
apache-2.0
adRichter/plantex,adRichter/plantex
44760832de165eed30214ca5a3cca71ef2556631
build.rs
build.rs
/* 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"...
/* 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"...
Use NUM_JOBS to control make -j
Use NUM_JOBS to control make -j
Rust
mpl-2.0
brendandahl/rust-azure,notriddle/rust-azure,vvuk/rust-azure,nox/rust-azure,nox/rust-azure,brendandahl/rust-azure,dzbarsky/rust-azure,nox/rust-azure,Adenilson/rust-azure,nox/rust-azure,brendandahl/rust-azure,servo/rust-azure,notriddle/rust-azure,dzbarsky/rust-azure,Adenilson/rust-azure,Adenilson/rust-azure,servo/rust-az...
6fce68a91046cd4f3824a82471dc3395d8461692
src/rust/src/lib.rs
src/rust/src/lib.rs
extern crate libc; use std::ffi::CStr; use std::os::raw::c_char; use libc::size_t; use libc::strncpy; mod rnc { #[test] fn add_i_i() { assert_eq!("II", add("I", "I")); } #[test] fn add_i_ii() { assert_eq!("III", add("I", "II")); } #[test] fn add_ii_iii() { ass...
extern crate libc; use std::ffi::CStr; use std::os::raw::c_char; use libc::size_t; use libc::strncpy; mod rnc { pub fn add(num_l: &str, num_r: &str) -> String { let sum = String::from(num_l) + num_r; if sum == "IIIII" { String::from("V") } else { sum } ...
Use more idiomatic rust testing
Use more idiomatic rust testing
Rust
mit
ben--/kata-rnc,ben--/kata-rnc,ben--/kata-rnc
fbe1b8e31397f4afaf237e74455ef1fe91cbc7a9
src/lib/builtins/conditionals.rs
src/lib/builtins/conditionals.rs
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_arg...
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_arg...
Change starts-with, ends-with and contains builtin descriptions
Change starts-with, ends-with and contains builtin descriptions
Rust
mit
redox-os/ion,redox-os/ion,redox-os/ion
9fc6737e1bb5048b26bf3478753cb1483017fa50
src/maybe_uninit_copy.rs
src/maybe_uninit_copy.rs
use array::Array; #[derive(Copy, Clone)] pub union MaybeUninitCopy<T> where T: Copy { empty: (), value: T, } impl<T> MaybeUninitCopy<T> where T: Copy { /// Create a new MaybeUninit with uninitialized interior pub unsafe fn uninitialized() -> Self { Self { empty: () } } /// Cr...
use array::Array; #[derive(Copy, Clone)] #[repr(C)] // for cast from self ptr to value pub union MaybeUninitCopy<T> where T: Copy { empty: (), value: T, } impl<T> MaybeUninitCopy<T> where T: Copy { /// Create a new MaybeUninit with uninitialized interior pub unsafe fn uninitialized() -> Self ...
Use repr(C) MaybeUninitCopy after discussion with RalfJung
FIX: Use repr(C) MaybeUninitCopy after discussion with RalfJung We have a recommendation from the unsafe-wg (no rule yet), that repr(C) for unions should work this way, so that we can cast from the union type to one of its fields.
Rust
apache-2.0
bluss/arrayvec
b111838732f51cff1a74a88825ff1920c08549b8
examples/basic.rs
examples/basic.rs
#![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!("...
#![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"...
Update example for new plugin.
Update example for new plugin.
Rust
apache-2.0
huonw/compile_msg
5d6fbf05936a0fd1d58800ab1d9b9d73b4b69a8c
proto/protomvc.rs
proto/protomvc.rs
use std::os::getenv; struct Request { path: ~str, querystring: ~str } fn main() { print("content-type: text/plain\r\n\r\n"); println("hello from rust!"); let req=Request{ path: getenv("PATH_INFO").unwrap_or(~""), querystring: getenv("QUERY_STRING").unwrap_or(~"")}; println!("path: {:s}", req....
use std::os::getenv; struct Request { path: ~str, querystring: ~str } impl Request { fn populate() -> Request { Request{ path: getenv("PATH_INFO").unwrap_or(~""), querystring: getenv("QUERY_STRING").unwrap_or(~"") } } } struct Route { path: ~str, handl...
Add route structure and handlers
Add route structure and handlers
Rust
bsd-3-clause
Earlz/rustymvc,tempbottle/rustymvc
dab90f7b91a6000fe874e3d664f244048e5fa342
exercises/conversions/as_ref_mut.rs
exercises/conversions/as_ref_mut.rs
// AsRef and AsMut allow for cheap reference-to-reference conversions. // Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html // and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // I AM NOT DONE // Obtain the number of bytes (not characters) in the given argument // ...
// AsRef and AsMut allow for cheap reference-to-reference conversions. // Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html // and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // Obtain the number of bytes (not characters) in the given argument // Add the AsRef tra...
Remove duplicate not done comment
Remove duplicate not done comment As indicated in #259 , I found it confusing to have 2 comments as the code wouldn't compile unless I solved both issues (I used the script from #281 to remove a comment and use `:wn` to go to next exercise, hence this tripped me).
Rust
mit
carols10cents/rustlings,carols10cents/rustlings
90b4f4ece65a0f45e8448fb636536a63bc9ca0b6
src/io/operations/mod.rs
src/io/operations/mod.rs
//! Netherrack-specific I/O operations for Rust pub mod reader; pub mod writer; #[cfg(test)] mod test { use super::reader::NetherrackReader; use super::writer::NetherrackWriter; use std::io::Cursor; #[test] fn test_read_write_unsigned_varint_32() { let mut vector = Cursor::new(vec![0u...
//! Netherrack-specific I/O operations for Rust pub mod reader; pub mod writer; #[cfg(test)] mod test { use super::reader::NetherrackReader; use super::writer::NetherrackWriter; use std::io::Cursor; #[test] fn test_read_write_unsigned_varint_32() { let mut vector = Cursor::new(vec![0u...
Test native use of Varint32 zero
Test native use of Varint32 zero
Rust
apache-2.0
Techern/Netherrack
3a8d90bc6d0cd14a43dc3da322e7260cd6f751d4
src/uniform_data.rs
src/uniform_data.rs
use std::slice; use std::mem; pub enum UniformPrimitiveType { Float, Int } pub enum UniformDatumType { Vec1(UniformPrimitiveType), Vec2(UniformPrimitiveType), Vec3(UniformPrimitiveType), Vec4(UniformPrimitiveType), Matrix2x2, Matrix3x3, Matrix4x4 } pub trait UniformData { fn u...
use std::slice; use std::mem; pub enum UniformPrimitiveType { Float, Int } pub enum UniformDatumType { Vec1(UniformPrimitiveType), Vec2(UniformPrimitiveType), Vec3(UniformPrimitiveType), Vec4(UniformPrimitiveType), Matrix2x2, Matrix3x3, Matrix4x4 } pub trait UniformData { fn u...
Add impls of `UniformPrimitive` for `f32` and `i32`
Add impls of `UniformPrimitive` for `f32` and `i32`
Rust
apache-2.0
kylewlacy/glitter,kylewlacy/glitter
b65059812a2b366550c6622608410a5f22aebded
protobuf/src/misc.rs
protobuf/src/misc.rs
use std::mem; use std::slice; /// Slice from `vec[vec.len()..vec.capacity()]` pub unsafe fn remaining_capacity_as_slice_mut<A>(vec: &mut Vec<A>) -> &mut [A] { slice::from_raw_parts_mut( vec.as_mut_slice().as_mut_ptr().offset(vec.len() as isize), vec.capacity() - vec.len(), ) } pub unsafe fn re...
use std::mem; /// Slice from `vec[vec.len()..vec.capacity()]` pub unsafe fn remaining_capacity_as_slice_mut<A>(vec: &mut Vec<A>) -> &mut [A] { let range = vec.len()..vec.capacity(); vec.get_unchecked_mut(range) } pub unsafe fn remove_lifetime_mut<A: ?Sized>(a: &mut A) -> &'static mut A { mem::transmute(a)...
Simplify internal function a bit
Simplify internal function a bit
Rust
mit
stepancheg/rust-protobuf,stepancheg/rust-protobuf,stepancheg/rust-protobuf
7f388d551a37a12e329dadf3f692905f6038f0e3
src/traversal.rs
src/traversal.rs
use {HashSet}; use std::collections::{HashMap, RingBuf, Deque}; use graph::{Graph, NodeIndex, Digraph}; /// Do a breadth-first search of the graph, returning the resulting breadth- /// first forest. fn bfs_forest<T, G: Graph<T>>(g: &G, start: NodeIndex) -> Digraph<NodeIndex> { let mut forest = Digraph::new(); ...
use {HashSet}; use std::collections::{HashMap, RingBuf, Deque}; use graph::{Graph, NodeIndex, Digraph}; /// Do a breadth-first search of the graph, returning the resulting breadth- /// first tree (a tree on the connected component containing the stard node) fn bfs_tree<T, G: Graph<T>>(g: &G, start: NodeIndex) -> Digra...
Change bfs to not traverse all the connected components.
Change bfs to not traverse all the connected components.
Rust
mit
nham/gymnosporangium
80c0ec7ac4045c8a7fe60020ffcb4a51788c5f92
src/generator.rs
src/generator.rs
extern crate liquid; use grammar::{LexicalUnit, ProductionRule, RuleComponent, Grammar}; use self::liquid::{Renderable, Context, Value, FilterError}; static template : &'static str = include_str!("parser.liquid"); pub fn generate(grammar: Grammar) { let tmplt = liquid::parse(template, Default::default()).unwrap(...
extern crate liquid; use grammar::{LexicalUnit, ProductionRule, RuleComponent, Grammar}; use self::liquid::{Renderable, Context, Value, FilterError}; use std::fs::File; use std::io; use std::io::Write; static template : &'static str = include_str!("parser.liquid"); pub fn generate(grammar: Grammar) { let tmplt =...
Write the generated code into a file
Write the generated code into a file
Rust
mit
Shiroy/lalr_gen
ae65e0c8f478878477dae459b2a26aa1e8c4f47f
src/main.rs
src/main.rs
use std::net::TcpStream; use std::io::prelude::*; fn main() { let mut connection = TcpStream::connect("127.0.0.1:6667").unwrap(); let _ = connection.write(b"Hello World\n"); let mut bytes = connection.bytes(); const COMMAND_BUF_SIZE: usize = 4096; let mut command_buf: [u8; COMMAND_BUF_SIZE] = [0; COMMAND_BUF_SIZE...
use std::net::TcpStream; use std::io::prelude::*; use std::str; fn main() { let mut connection = TcpStream::connect("127.0.0.1:6667").unwrap(); let _ = connection.write(b"Hello World\n"); let mut bytes = connection.bytes(); const COMMAND_BUF_SIZE: usize = 4096; let mut command_buf: [u8; COMMAND_BUF_SIZE] = [0; CO...
Create str from command arr
Create str from command arr
Rust
mit
nickmass/rust-irc
9b8382264c8b48bcd67bdb3984383fda3ce2a3c0
build.rs
build.rs
use std::process::Command; fn git_hash() -> String { let output = Command::new("git") .args(&["rev-parse", "--short", "HEAD"]) .output() .unwrap(); String::from_utf8_lossy(&output.stdout).into() } fn main() { let git_hash = option_env!("TRAVIS_COMMIT") .map(|s| s.into()) ...
use std::process::Command; fn git_hash() -> String { let output = Command::new("cat") .args(&[".git/refs/heads/next"]) .output() .unwrap(); String::from_utf8_lossy(&output.stdout).into() } fn main() { let git_hash = option_env!("TRAVIS_COMMIT") .map(|s| s.into()) .u...
Use cat to get get sha.
Use cat to get get sha. cross docker image doesn't have git command.
Rust
mit
autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/L...
b27141a77ad908f15269bf503fd1a21733582dc0
build.rs
build.rs
extern crate "pkg-config" as pkg_config; use std::os; use std::old_io::{self, fs, Command}; use std::old_io::process::InheritFd; fn main() { match pkg_config::find_library("sass") { Ok(_) => return, Err(_) => {} } let src = Path::new(os::getenv("CARGO_MANIFEST_DIR").unwrap()); let mut c...
extern crate "pkg-config" as pkg_config; use std::os; use std::old_io::{self, fs, Command}; use std::old_io::process::InheritFd; fn main() { match pkg_config::find_library("sass") { Ok(_) => return, Err(_) => {} } let src = Path::new(os::getenv("CARGO_MANIFEST_DIR").unwrap()); let mut c...
Use explicit path for library
Use explicit path for library
Rust
mit
Keats/sass-sys
43b133f292b9500df1962fb649ea24fdef4e02ad
src/asset_store.rs
src/asset_store.rs
//! Storing sounds, textures, animations etc. // Extern crates. use std::os::self_exe_path; /// A place to store sounds, textures, animations etc. /// /// The idea is to have one object which the app can use /// to load assets for the game with a simple interface. pub struct AssetStore { // The folder to load as...
//! Storing sounds, textures, animations etc. // Extern crates. use std::os::self_exe_path; /// A place to store sounds, textures, animations etc. /// /// The idea is to have one object which the app can use /// to load assets for the game with a simple interface. pub struct AssetStore { // The folder to load as...
Make `AssetStore` return Err when empty
Make `AssetStore` return Err when empty Closes https://github.com/PistonDevelopers/piston/issues/432
Rust
mit
KevinFrans3/piston,axelmagn/piston,getynge/piston,PistonDevelopers/piston,PistonDevelopers/piston,caldwell/piston,oldmanmike/piston,mitchmindtree/piston,bvssvni/piston,bvssvni/piston,placrosse/piston,Potpourri/piston,tempbottle/piston
2af53e9a15aed1e9798867c9233a722530d03177
src/test/ui/tls.rs
src/test/ui/tls.rs
// run-pass #![feature(thread_local)] #[thread_local] static S: u32 = 222; fn main() { let local = &S as *const u32 as usize; let foreign = std::thread::spawn(|| &S as *const u32 as usize).join().unwrap(); assert_ne!(local, foreign); }
// run-pass // compile-flags: -O #![feature(thread_local)] #[thread_local] static S: u32 = 222; fn main() { let local = &S as *const u32 as usize; let foreign = std::thread::spawn(|| &S as *const u32 as usize).join().unwrap(); assert_ne!(local, foreign); }
Add -O compile flag to test
Add -O compile flag to test
Rust
apache-2.0
graydon/rust,graydon/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,graydon/rust,aidancully/rust,aidancully/rust,aidancully/rust,aidancully/rust,graydon/rust
0c3050489f3f21849d5c05d0a189a7677436e189
src/frame/decoder.rs
src/frame/decoder.rs
use frame::ChannelAssignment; fn decode_left_side(buffer: &mut [i32]) { let block_size = buffer.len() / 2; for i in 0..block_size { let left = buffer[i]; let side = buffer[i + block_size]; // right channel buffer[i + block_size] = left - side; } } pub fn decode(channel_assignment: ChannelAssig...
use frame::ChannelAssignment; fn decode_left_side(buffer: &mut [i32]) { let block_size = buffer.len() / 2; for i in 0..block_size { let left = buffer[i]; let side = buffer[i + block_size]; // right channel buffer[i + block_size] = left - side; } } fn decode_right_side(buffer: &mut [i32]) { l...
Add implementation for `RightSide` decoding
Add implementation for `RightSide` decoding
Rust
bsd-3-clause
sourrust/flac
44f7fe9ea2942c9c5a6b0606eef7b5d6292a1cf5
src/main.rs
src/main.rs
extern crate ai; use ai::agent::Agent; use ai::environment::Environment; use ai::environment::CoinFlip; use ai::random::RandomImpl; use ai::types::{Action, Observation, Reward}; // Without this, cargo test warns that "main" is unused. #[cfg_attr(test, allow(dead_code))] fn main() { // Use one RNG to bootstrap the o...
extern crate ai; use ai::agent::Agent; use ai::environment::Environment; use ai::environment::CoinFlip; use ai::random::RandomImpl; use ai::types::Reward; // Without this, cargo test warns that "main" is unused. #[cfg_attr(test, allow(dead_code))] fn main() { // Use one RNG to bootstrap the others so that we only h...
Remove the last build and run warnings.
Remove the last build and run warnings.
Rust
mit
dinowernli/marvin
4054bf238f66623be2a861502ff79b612d60396b
src/main.rs
src/main.rs
mod vm; mod command; mod parse; mod program; use vm::VM; use program::Program; use std::io::Write; fn main() { let mut vm = VM::new(); let mut program = Program::new(); loop { print!("{}", "bf> "); std::io::stdout().flush().unwrap(); let mut line = String::new(); let comma...
mod vm; mod command; mod parse; mod program; use vm::VM; use program::Program; use std::io::Write; fn main() { let mut vm = VM::new(); let mut program = Program::new(); loop { print!("{}", if program.is_seeking {"... "} else {"bf> "}); std::io::stdout().flush().unwrap(); let mut l...
Change prompt based upon potential loop nesting
Change prompt based upon potential loop nesting
Rust
mit
nafarlee/thoughtfuck
776deb6b9f326f5ba5984e4d55cb5010a17ce559
src/test/ui/tuple/nested-index.rs
src/test/ui/tuple/nested-index.rs
// run-pass fn main () { let n = (1, (2, 3)).1.1; assert_eq!(n, 3); let n = (1, (2, (3, 4))).1.1.1; assert_eq!(n, 4); }
// run-pass fn main () { let n = (1, (2, 3)).1.1; assert_eq!(n, 3); let n = (1, (2, (3, 4))).1.1.1; assert_eq!(n, 4); // This is a range expression, not nested indexing. let _ = 0.0..1.1; }
Test a range, which is not nested indexing
Test a range, which is not nested indexing
Rust
apache-2.0
graydon/rust,aidancully/rust,graydon/rust,graydon/rust,graydon/rust,graydon/rust,aidancully/rust,aidancully/rust,aidancully/rust,aidancully/rust,graydon/rust,aidancully/rust
9cb99ff0f63f19a1a193b1eef545a37cd531d9c1
2/10/src/aes_cbc.rs
2/10/src/aes_cbc.rs
/* AES-128 CBC mode * * Dmitry Vasiliev <dima@hlabs.org> */ extern crate serialize; extern crate aes_lib; use std::path::Path; use std::io::fs::File; use std::iter::repeat; use serialize::base64::FromBase64; use aes_lib::{decrypt_aes_cbc, encrypt_aes_cbc}; fn read_hex_file(path: &Path) -> Vec<u8> { match F...
/* AES-128 CBC mode * * Dmitry Vasiliev <dima@hlabs.org> */ extern crate serialize; extern crate aes_lib; use std::path::Path; use std::io::fs::File; use serialize::base64::FromBase64; use aes_lib::{decrypt_aes_cbc, encrypt_aes_cbc}; fn read_hex_file(path: &Path) -> Vec<u8> { match File::open(path) { ...
Replace repeat() with static array
Replace repeat() with static array
Rust
mit
hdima/matasano-crypto-challenges
d342fdbb3af88cbf711592cc5182706d7628417e
exercises/grade-school/example.rs
exercises/grade-school/example.rs
use std::collections::HashMap; pub struct School { grades: HashMap<u32, Vec<String>> } impl School { pub fn new() -> School { School { grades: HashMap::new() } } pub fn add(&mut self, grade: u32, student: &str) { let mut entry = self.grades.entry(grade).or_insert(Vec::new()); ...
use std::collections::HashMap; pub struct School { grades: HashMap<u32, Vec<String>> } impl School { pub fn new() -> School { School { grades: HashMap::new() } } pub fn add(&mut self, grade: u32, student: &str) { let mut entry = self.grades.entry(grade).or_insert(Vec::new()); ...
Use `cloned` instead of `map(|k| k.clone())`
grade-school: Use `cloned` instead of `map(|k| k.clone())` They're equivalent, but I figure if there's already a function that does the clone, might as well use it instead of `map` and making someone read the body of the map.
Rust
mit
exercism/xrust,sacherjj/rust,exercism/xrust,sacherjj/rust,petertseng/exercism-rust,petertseng/exercism-rust,sacherjj/rust,petertseng/exercism-rust
b7cdee8d0f461eb4013fb7cfe7a98f7cc66a63fe
benches/generate.rs
benches/generate.rs
#![feature(test)] extern crate identicon; extern crate md_5 as md5; extern crate test; use md5::{Digest, Md5}; use test::Bencher; use identicon::Identicon; #[bench] fn generate(x: &mut Bencher) { let input = "42".as_bytes(); let bytes = Md5::digest(input); let identicon = Identicon::new(bytes.as_slice()...
#![feature(test)] extern crate identicon; extern crate md_5 as md5; extern crate test; use md5::{Digest, Md5}; use test::Bencher; use identicon::Identicon; #[bench] fn generate(x: &mut Bencher) { let input = "42".as_bytes(); let bytes = Md5::digest(input); let identicon = Identicon::new(&bytes); x.i...
Use deref coercion to borrow byte slice
Use deref coercion to borrow byte slice
Rust
mit
dgraham/identicon
a7b1a5997f386171604b81e689b293c03d64324a
src/worker/mod.rs
src/worker/mod.rs
mod immediate; #[cfg(feature = "std")] mod multithreaded; #[cfg(all(feature = "std", not(any(target_arch = "asmjs", target_arch = "wasm32"))))] pub use self::multithreaded::MultiThreadedWorker as PlatformWorker; #[cfg(any(not(feature = "std"), target_arch = "asmjs", target_arch = "wasm32"))] pub use self::immediate::I...
mod immediate; mod multithreaded; #[cfg(not(any(target_arch = "asmjs", target_arch = "wasm32")))] pub use self::multithreaded::MultiThreadedWorker as PlatformWorker; #[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))] pub use self::immediate::ImmediateWorker as PlatformWorker; use alloc::sync::Arc; use alloc::...
Remove feature gate on the std feature
Remove feature gate on the std feature
Rust
apache-2.0
image-rs/jpeg-decoder