file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
specialization-no-default.rs
// 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 ...
(&self) {} fn bar(&self) {} } impl Foo for u8 {} impl Foo for u16 { fn foo(&self) {} //~ ERROR E0520 } impl Foo for u32 { fn bar(&self) {} //~ ERROR E0520 } //////////////////////////////////////////////////////////////////////////////// // Test 2: one layer of specialization, missing `default` on associa...
foo
identifier_name
specialization-no-default.rs
// 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 ...
} impl<T: Clone> Baz for T { fn baz(&self) {} } impl Baz for i32 { fn baz(&self) {} //~ ERROR E0520 } //////////////////////////////////////////////////////////////////////////////// // Test 3b: multiple layers of specialization, missing interior `default`, // redundant `default` in bottom layer. ///////////...
default fn baz(&self) {}
random_line_split
specialization-no-default.rs
// 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 ...
} impl Foo for u8 {} impl Foo for u16 { fn foo(&self) {} //~ ERROR E0520 } impl Foo for u32 { fn bar(&self) {} //~ ERROR E0520 } //////////////////////////////////////////////////////////////////////////////// // Test 2: one layer of specialization, missing `default` on associated type //////////////////////...
{}
identifier_body
main.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
() { println!("Hello, world!"); let args: Vec<_> = std::env::args().collect(); if args.len() < 2 { println!("Usage: {} ", args[0]); return; } let fname = std::path::Path::new(&*args[1]); let file = fs::File::open(&fname).unwrap(); let mut archive = zip::ZipArchive::new(file...
main
identifier_name
main.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
return; } let fname = std::path::Path::new(&*args[1]); let file = fs::File::open(&fname).unwrap(); let mut archive = zip::ZipArchive::new(file).unwrap(); for i in 0..archive.len() { let mut file = archive.by_index(i); print_file(file); } } fn print_file<'a>( in_fil...
println!("Hello, world!"); let args: Vec<_> = std::env::args().collect(); if args.len() < 2 { println!("Usage: {} <filename>", args[0]);
random_line_split
main.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
let fname = std::path::Path::new(&*args[1]); let file = fs::File::open(&fname).unwrap(); let mut archive = zip::ZipArchive::new(file).unwrap(); for i in 0..archive.len() { let mut file = archive.by_index(i); print_file(file); } } fn print_file<'a>( in_file: zip::result::ZipRe...
{ println!("Usage: {} <filename>", args[0]); return; }
conditional_block
main.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
fn print_file<'a>( in_file: zip::result::ZipResult<zip::read::ZipFile>, ) -> zip::result::ZipResult<()> { let file = in_file?; println!("read file: {:?}", file.sanitized_name()); return Ok(()); }
{ println!("Hello, world!"); let args: Vec<_> = std::env::args().collect(); if args.len() < 2 { println!("Usage: {} <filename>", args[0]); return; } let fname = std::path::Path::new(&*args[1]); let file = fs::File::open(&fname).unwrap(); let mut archive = zip::ZipArchive::n...
identifier_body
task-comm-16.rs
// Copyright 2012 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 ...
fn test_str() { let (tx, rx) = channel(); let s0 = ~"test"; tx.send(s0); let s1 = rx.recv(); assert_eq!(s1[0], 't' as u8); assert_eq!(s1[1], 'e' as u8); assert_eq!(s1[2],'s' as u8); assert_eq!(s1[3], 't' as u8); } #[deriving(Show)] enum t { tag1, tag2(int), tag3(int, u8, c...
{ let (tx, rx) = channel(); let v0: Vec<int> = vec!(0, 1, 2); tx.send(v0); let v1 = rx.recv(); assert_eq!(*v1.get(0), 0); assert_eq!(*v1.get(1), 1); assert_eq!(*v1.get(2), 2); }
identifier_body
task-comm-16.rs
// Copyright 2012 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 ...
{val0: int, val1: u8, val2: char} let (tx, rx) = channel(); let r0: R = R {val0: 0, val1: 1u8, val2: '2'}; tx.send(r0); let mut r1: R; r1 = rx.recv(); assert_eq!(r1.val0, 0); assert_eq!(r1.val1, 1u8); assert_eq!(r1.val2, '2'); } fn test_vec() { let (tx, rx) = channel(); let v0...
R
identifier_name
task-comm-16.rs
// Copyright 2012 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 ...
fn eq(&self, other: &t) -> bool { match *self { tag1 => { match (*other) { tag1 => true, _ => false } } tag2(e0a) => { match (*other) { tag2(e0b) => e0a == e0b, ...
tag2(int), tag3(int, u8, char) } impl cmp::Eq for t {
random_line_split
lib.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/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
} macro_rules! reexport_computed_values { ( $( $name: ident )+ ) => { /// Types for [computed values][computed]. /// /// [computed]: https://drafts.csswg.org/css-cascade/#computed pub mod computed_values { $( pub use properties::longhands::$name::computed...
#[allow(unsafe_code)] pub mod properties { include!(concat!(env!("OUT_DIR"), "/properties.rs"));
random_line_split
resto_druid_mastery.rs
extern crate wow_combat_log; extern crate chrono; extern crate clap; use std::fs::File; use std::io::BufReader; use std::collections::{HashMap, HashSet}; use std::fmt; use chrono::Duration; use clap::{Arg, App}; use wow_combat_log::Entry; static MASTERY_AURAS: &'static [u32] = &[ 33763, // Lifebloom 774, // R...
// Only measure the contribution to other heals if aura!= id { let added = (unmast as f64 * mastery) as u64; *self.hot_mastery_healing_added.entry(aura).or_insert(0) += added; } ...
for &aura in &entry.0 {
random_line_split
resto_druid_mastery.rs
extern crate wow_combat_log; extern crate chrono; extern crate clap; use std::fs::File; use std::io::BufReader; use std::collections::{HashMap, HashSet}; use std::fmt; use chrono::Duration; use clap::{Arg, App}; use wow_combat_log::Entry; static MASTERY_AURAS: &'static [u32] = &[ 33763, // Lifebloom 774, // R...
if log.base().is_none() { return; } let base = log.base().unwrap(); if base.src.id!= self.player_id { return; } let entry = self.map.entry(log.base().unwrap().dst.id).or_insert((HashSet::new(), log.timestamp())); let diff = log.timestamp() ...
{ use wow_combat_log::Entry::*; use wow_combat_log::AuraType::*; if let Info { id, mastery, ref auras, .. } = *log { let entry = self.map.entry(id).or_insert((HashSet::new(), log.timestamp())); let player_id = self.player_id; if player_id == id { ...
identifier_body
resto_druid_mastery.rs
extern crate wow_combat_log; extern crate chrono; extern crate clap; use std::fs::File; use std::io::BufReader; use std::collections::{HashMap, HashSet}; use std::fmt; use chrono::Duration; use clap::{Arg, App}; use wow_combat_log::Entry; static MASTERY_AURAS: &'static [u32] = &[ 33763, // Lifebloom 774, // R...
<'a, I: Iterator<Item=Entry<'a>>>(iter: I, player: &str) -> Option<(&'a str, u32)> { let mut map = HashMap::new(); let mut player_id = None; for log in iter { if player_id.is_none() { if let Some(base) = log.base() { let id; if base.src.name == player { ...
find_init_mastery
identifier_name
type_names.rs
// 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 ...
push_type_params(cx, substs, output); }, ty::TyTuple(ref component_types) => { output.push('('); for &component_type in component_types { push_debuginfo_type_name(cx, component_type, true, output); output.push_str(", "); } ...
{ match t.sty { ty::TyBool => output.push_str("bool"), ty::TyChar => output.push_str("char"), ty::TyStr => output.push_str("str"), ty::TyInt(ast::TyIs) => output.push_str("isize"), ty::TyInt(ast::TyI8) => output.push_str("i8"), ...
identifier_body
type_names.rs
// 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 ...
ty::TyFloat(ast::TyF64) => output.push_str("f64"), ty::TyStruct(def_id, substs) | ty::TyEnum(def_id, substs) => { push_item_name(cx, def_id, qualified, output); push_type_params(cx, substs, output); }, ty::TyTuple(ref component_types) => { outp...
ty::TyUint(ast::TyU64) => output.push_str("u64"), ty::TyFloat(ast::TyF32) => output.push_str("f32"),
random_line_split
type_names.rs
// 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 ...
<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, qualified: bool) -> String { let mut result = String::with_capacity(64); push_debuginfo_type_name(cx, t, qualified, &mut res...
compute_debuginfo_type_name
identifier_name
type_names.rs
// 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 ...
let mut path_element_count = 0; for path_element in path { let name = token::get_name(path_element.name()); output.push_str(&name); output.push_str("::"); path_element_count += 1; } ...
{ output.push_str(crate_root_namespace(cx)); output.push_str("::"); }
conditional_block
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
() { let service = IoService::<MyMessage>::start().expect("Error creating network service"); service.register_handler(Arc::new(MyHandler)).unwrap(); } }
test_service_register_handler
identifier_name
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
//! //! fn main () { //! let mut service = IoService::<MyMessage>::start().expect("Error creating network service"); //! service.register_handler(Arc::new(MyHandler)).unwrap(); //! //! // Wait for quit condition //! //... //! // Drop the service //! } //! ``` extern crate mio; #[macro_use] extern crate log as rlo...
//! } //! }
random_line_split
lib.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
/// Register a new stream with the event loop fn register_stream(&self, _stream: StreamToken, _reg: Token, _event_loop: &mut EventLoop<IoManager<Message>>) {} /// Re-register a stream with the event loop fn update_stream(&self, _stream: StreamToken, _reg: Token, _event_loop: &mut EventLoop<IoManager<Message>>) {} ...
{}
identifier_body
buf.rs
use alloc::heap::{Heap, Alloc, Layout}; use std::{cmp, io, mem, ops, ptr, slice}; use std::io::Write; /// Default buffer size. Perhaps this should be tunable. const BUF_SIZE: usize = 4096; /// A reference counted slab allocator. /// /// `MutBuf` keeps an internal byte buffer to which it allows bytes to be /// writte...
TestResult::passed() } quickcheck(fill as fn(Vec<u8>, Vec<u8>, Vec<u8>) -> TestResult); } }
{ return TestResult::failed(); }
conditional_block
buf.rs
use alloc::heap::{Heap, Alloc, Layout}; use std::{cmp, io, mem, ops, ptr, slice}; use std::io::Write; /// Default buffer size. Perhaps this should be tunable. const BUF_SIZE: usize = 4096; /// A reference counted slab allocator. /// /// `MutBuf` keeps an internal byte buffer to which it allows bytes to be /// writte...
/// /// `RawBuf` is not threadsafe, and may not be sent or shared across thread /// boundaries. struct RawBuf { bytes: *mut u8, len: usize, } impl RawBuf { /// Creates a new `RawBuf` instance with approximately the provided /// length. fn new(len: usize) -> RawBuf { unsafe { let...
/// It is left to the user to ensure that data races do not occur and /// unitialized data is not read.
random_line_split
buf.rs
use alloc::heap::{Heap, Alloc, Layout}; use std::{cmp, io, mem, ops, ptr, slice}; use std::io::Write; /// Default buffer size. Perhaps this should be tunable. const BUF_SIZE: usize = 4096; /// A reference counted slab allocator. /// /// `MutBuf` keeps an internal byte buffer to which it allows bytes to be /// writte...
quickcheck(buf as fn(Vec<Vec<u8>>) -> TestResult); } #[test] fn check_fill() { fn fill(segments: Vec<Vec<u8>>) -> TestResult { let total_len: usize = segments.iter().fold(0, |acc, segment| acc + segment.len()); let mut buf = MutBuf::with_capacity(total_len + 8); ...
{ fn buf(segments: Vec<Vec<u8>>) -> TestResult { let total_len: usize = segments.iter().fold(0, |acc, segment| acc + segment.len()); let mut buf = MutBuf::with_capacity(total_len + 8); for segment in &segments { buf.write_all(&*segment).unwrap(); ...
identifier_body
buf.rs
use alloc::heap::{Heap, Alloc, Layout}; use std::{cmp, io, mem, ops, ptr, slice}; use std::io::Write; /// Default buffer size. Perhaps this should be tunable. const BUF_SIZE: usize = 4096; /// A reference counted slab allocator. /// /// `MutBuf` keeps an internal byte buffer to which it allows bytes to be /// writte...
(&self, offset: usize, len: usize) -> Buf { unsafe { assert!(offset + len <= self.offset); Buf { raw: self.raw.clone(), ptr: self.raw.buf().offset(offset as isize), len: len, } } } /// Attempts to fill the buffe...
buf
identifier_name
offlineaudiocompletionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::audiobuffer::AudioBuffer; use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods...
#[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &OfflineAudioCompletionEventInit, ) -> Fallible<DomRoot<OfflineAudioCompletionEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::fro...
{ let event = Box::new(OfflineAudioCompletionEvent::new_inherited(rendered_buffer)); let ev = reflect_dom_object(event, window, OfflineAudioCompletionEventBinding::Wrap); { let event = ev.upcast::<Event>(); event.init_event(type_, bool::from(bubbles), bool::from(cancelabl...
identifier_body
offlineaudiocompletionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::audiobuffer::AudioBuffer; use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods...
(&self) -> DomRoot<AudioBuffer> { DomRoot::from_ref(&*self.rendered_buffer) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
RenderedBuffer
identifier_name
offlineaudiocompletionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::audiobuffer::AudioBuffer; use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods...
}
random_line_split
once.rs
use core; use Poll; use stream; use stream::Stream; /// A stream which emits single element and then EOF. /// /// This stream will never block and is always ready. #[must_use = "streams do nothing unless polled"] pub struct Once<T, E>(stream::IterStream<core::iter::Once<Result<T, E>>>); /// Creates a stream of singl...
<T, E>(item: Result<T, E>) -> Once<T, E> { Once(stream::iter(core::iter::once(item))) } impl<T, E> Stream for Once<T, E> { type Item = T; type Error = E; fn poll(&mut self) -> Poll<Option<T>, E> { self.0.poll() } }
once
identifier_name
once.rs
use core; use Poll; use stream; use stream::Stream; /// A stream which emits single element and then EOF. /// /// This stream will never block and is always ready. #[must_use = "streams do nothing unless polled"] pub struct Once<T, E>(stream::IterStream<core::iter::Once<Result<T, E>>>); /// Creates a stream of singl...
fn poll(&mut self) -> Poll<Option<T>, E> { self.0.poll() } }
type Error = E;
random_line_split
must_use-in-stdlib-traits.rs
#![deny(unused_must_use)] #![feature(futures_api, pin, arbitrary_self_types)] use std::iter::Iterator; use std::future::Future; use std::task::{Poll, LocalWaker}; use std::pin::Pin; use std::unimplemented; struct MyFuture; impl Future for MyFuture { type Output = u32; fn poll(self: Pin<&mut Self>, lw: &Local...
() { iterator(); //~ ERROR unused implementer of `std::iter::Iterator` that must be used future(); //~ ERROR unused implementer of `std::future::Future` that must be used square_fn_once(); //~ ERROR unused implementer of `std::ops::FnOnce` that must be used square_fn_mut(); //~ ERROR unused implementer of `...
main
identifier_name
must_use-in-stdlib-traits.rs
#![deny(unused_must_use)] #![feature(futures_api, pin, arbitrary_self_types)] use std::iter::Iterator; use std::future::Future; use std::task::{Poll, LocalWaker}; use std::pin::Pin; use std::unimplemented; struct MyFuture; impl Future for MyFuture { type Output = u32; fn poll(self: Pin<&mut Self>, lw: &Local...
fn square_fn_once() -> impl FnOnce(u32) -> u32 { |x| x * x } fn square_fn_mut() -> impl FnMut(u32) -> u32 { |x| x * x } fn square_fn() -> impl Fn(u32) -> u32 { |x| x * x } fn main() { iterator(); //~ ERROR unused implementer of `std::iter::Iterator` that must be used future(); //~ ERROR unused impleme...
MyFuture }
random_line_split
must_use-in-stdlib-traits.rs
#![deny(unused_must_use)] #![feature(futures_api, pin, arbitrary_self_types)] use std::iter::Iterator; use std::future::Future; use std::task::{Poll, LocalWaker}; use std::pin::Pin; use std::unimplemented; struct MyFuture; impl Future for MyFuture { type Output = u32; fn poll(self: Pin<&mut Self>, lw: &Local...
fn future() -> impl Future { MyFuture } fn square_fn_once() -> impl FnOnce(u32) -> u32 { |x| x * x } fn square_fn_mut() -> impl FnMut(u32) -> u32 { |x| x * x } fn square_fn() -> impl Fn(u32) -> u32 { |x| x * x } fn main() { iterator(); //~ ERROR unused implementer of `std::iter::Iterator` that must...
{ std::iter::empty::<u32>() }
identifier_body
install.rs
use crate::paths; use std::env::consts::EXE_SUFFIX; use std::path::{Path, PathBuf}; /// Used by `cargo install` tests to assert an executable binary /// has been installed. Example usage: /// /// assert_has_installed_exe(cargo_home(), "foo"); pub fn assert_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static ...
(name: &str) -> String { format!("{}{}", name, EXE_SUFFIX) }
exe
identifier_name
install.rs
use crate::paths; use std::env::consts::EXE_SUFFIX; use std::path::{Path, PathBuf}; /// Used by `cargo install` tests to assert an executable binary /// has been installed. Example usage: /// /// assert_has_installed_exe(cargo_home(), "foo"); pub fn assert_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static ...
pub fn assert_has_not_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) { assert!(!check_has_installed_exe(path, name)); } fn check_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) -> bool { path.as_ref().join("bin").join(exe(name)).is_file() } pub fn cargo_home() -> PathBuf { pat...
{ assert!(check_has_installed_exe(path, name)); }
identifier_body
install.rs
use crate::paths; use std::env::consts::EXE_SUFFIX; use std::path::{Path, PathBuf};
/// assert_has_installed_exe(cargo_home(), "foo"); pub fn assert_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) { assert!(check_has_installed_exe(path, name)); } pub fn assert_has_not_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) { assert!(!check_has_installed_exe(path, name));...
/// Used by `cargo install` tests to assert an executable binary /// has been installed. Example usage: ///
random_line_split
config_env.rs
use envconfig::Envconfig; use crate::domain::key_derivation::KeyDerivationFunction; lazy_static! { static ref APP_ENV_CONFIG: AppEnvConfig = AppEnvConfig::init().unwrap(); } pub fn get_app_env_config() -> &'static AppEnvConfig { return &APP_ENV_CONFIG } #[derive(Envconfig, Debug)] pub struct AppEnvConfig { ...
}
{ env::remove_var("NEW_AGENT_KDF"); let app_config = AppEnvConfig::init().unwrap(); assert_eq!(app_config.new_agent_kdf, KeyDerivationFunction::Raw, "Default new_agent_kdf should be Raw"); env::set_var("NEW_AGENT_KDF", "RAW"); let app_config = AppEnvConfig::init().unwrap(); ...
identifier_body
config_env.rs
use envconfig::Envconfig; use crate::domain::key_derivation::KeyDerivationFunction; lazy_static! { static ref APP_ENV_CONFIG: AppEnvConfig = AppEnvConfig::init().unwrap(); } pub fn get_app_env_config() -> &'static AppEnvConfig { return &APP_ENV_CONFIG } #[derive(Envconfig, Debug)] pub struct
{ #[envconfig(from = "NEW_AGENT_KDF", default = "RAW")] pub new_agent_kdf: KeyDerivationFunction, #[envconfig(from = "RESTORE_ON_DEMAND", default = "false")] pub restore_on_demand: bool, } #[cfg(test)] mod tests { use super::*; use std::env; #[test] fn should_construct_app_env_config_...
AppEnvConfig
identifier_name
config_env.rs
use envconfig::Envconfig; use crate::domain::key_derivation::KeyDerivationFunction; lazy_static! { static ref APP_ENV_CONFIG: AppEnvConfig = AppEnvConfig::init().unwrap(); } pub fn get_app_env_config() -> &'static AppEnvConfig { return &APP_ENV_CONFIG } #[derive(Envconfig, Debug)] pub struct AppEnvConfig { ...
env::set_var("NEW_AGENT_KDF", "RAW"); let app_config = AppEnvConfig::init().unwrap(); assert_eq!(app_config.new_agent_kdf, KeyDerivationFunction::Raw, "Expected new_agent_kdf to be Raw."); env::set_var("NEW_AGENT_KDF", "ARGON2I_INT"); let app_config = AppEnvConfig::init().unwrap...
fn should_construct_app_env_config_with_correct_kdf() { env::remove_var("NEW_AGENT_KDF"); let app_config = AppEnvConfig::init().unwrap(); assert_eq!(app_config.new_agent_kdf, KeyDerivationFunction::Raw, "Default new_agent_kdf should be Raw");
random_line_split
tx_processor.rs
// Copyright 2018 Mozilla // // 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...
{} pub struct DatomsIterator<'dbtx, 't, T> where T: Sized + Iterator<Item=Result<TxPart>> + 't { at_first: bool, at_last: bool, first: &'dbtx TxPart, rows: &'t mut Peekable<T>, } impl<'dbtx, 't, T> DatomsIterator<'dbtx, 't, T> where T: Sized + Iterator<Item=Result<TxPart>> + 't { fn new(first: &'...
Processor
identifier_name
tx_processor.rs
// Copyright 2018 Mozilla // // 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...
/// Implementors must specify type of the "receiver report" which /// they will produce once processor is finished. pub trait TxReceiver<RR> { /// Called for each transaction, with an iterator over its datoms. fn tx<T: Iterator<Item=TxPart>>(&mut self, tx_id: Entid, d: &mut T) -> Result<()>; /// Called once...
TxPart, };
random_line_split
tx_processor.rs
// Copyright 2018 Mozilla // // 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...
} impl<'dbtx, 't, T> Iterator for DatomsIterator<'dbtx, 't, T> where T: Sized + Iterator<Item=Result<TxPart>> + 't { type Item = TxPart; fn next(&mut self) -> Option<Self::Item> { if self.at_last { return None; } if self.at_first { self.at_first = false; ...
{ DatomsIterator { at_first: true, at_last: false, first: first, rows: rows, } }
identifier_body
extern-crate-referenced-by-self-path.rs
// Copyright 2018 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 ...
() { foo(); }
main
identifier_name
extern-crate-referenced-by-self-path.rs
// Copyright 2018 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 ...
{ foo(); }
identifier_body
extern-crate-referenced-by-self-path.rs
// Copyright 2018 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 ...
foo(); }
random_line_split
lib.rs
extern crate num; use num::traits::identities::Zero; use std::cmp::PartialOrd; pub struct Triangle<T: Zero + PartialOrd + Copy>([T; 3]); impl<T: Zero + PartialOrd + Copy> Triangle<T> { pub fn build(lengths: [T; 3]) -> Result<Triangle<T>, &'static str> { if lengths[0] <= T::zero() || lengths[1] <= T::zero...
// two sides are equal, but not all three !self.is_equilateral() && (self.0[0] == self.0[1] || self.0[1] == self.0[2] || self.0[2] == self.0[0]) } pub fn is_scalene(&self) -> bool { // all sides differently, no two sides equal self.0[0]!= self.0[1] && self.0[1]!= self.0[2]...
pub fn is_isosceles(&self) -> bool {
random_line_split
lib.rs
extern crate num; use num::traits::identities::Zero; use std::cmp::PartialOrd; pub struct
<T: Zero + PartialOrd + Copy>([T; 3]); impl<T: Zero + PartialOrd + Copy> Triangle<T> { pub fn build(lengths: [T; 3]) -> Result<Triangle<T>, &'static str> { if lengths[0] <= T::zero() || lengths[1] <= T::zero() || lengths[2] <= T::zero() { Err("Zero sized sides are illegal") } else if!(l...
Triangle
identifier_name
lib.rs
extern crate num; use num::traits::identities::Zero; use std::cmp::PartialOrd; pub struct Triangle<T: Zero + PartialOrd + Copy>([T; 3]); impl<T: Zero + PartialOrd + Copy> Triangle<T> { pub fn build(lengths: [T; 3]) -> Result<Triangle<T>, &'static str> { if lengths[0] <= T::zero() || lengths[1] <= T::zero...
else if!(lengths[0] + lengths[1] > lengths[2] && lengths[1] + lengths[2] > lengths[0] && lengths[2] + lengths[0] > lengths[1]) { Err("Triangle inequality does not hold") } else { Ok(Triangle(lengths)) } } pub fn is_equilateral(&self) -> bool { ...
{ Err("Zero sized sides are illegal") }
conditional_block
lib.rs
extern crate num; use num::traits::identities::Zero; use std::cmp::PartialOrd; pub struct Triangle<T: Zero + PartialOrd + Copy>([T; 3]); impl<T: Zero + PartialOrd + Copy> Triangle<T> { pub fn build(lengths: [T; 3]) -> Result<Triangle<T>, &'static str> { if lengths[0] <= T::zero() || lengths[1] <= T::zero...
pub fn is_scalene(&self) -> bool { // all sides differently, no two sides equal self.0[0]!= self.0[1] && self.0[1]!= self.0[2] && self.0[2]!= self.0[0] } }
{ // two sides are equal, but not all three !self.is_equilateral() && (self.0[0] == self.0[1] || self.0[1] == self.0[2] || self.0[2] == self.0[0]) }
identifier_body
fnv.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/. */ //! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs use std::default::Default; use std::hash::...
() -> FnvHasher { FnvHasher(0xcbf29ce484222325) } } impl Hasher for FnvHasher { type Output = u64; fn reset(&mut self) { *self = Default::default(); } fn finish(&self) -> u64 { self.0 } } impl Writer for FnvHasher { fn write(&mut self, bytes: &[u8]) { let FnvHasher(mut hash) = *self; f...
default
identifier_name
fnv.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/. */ //! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs use std::default::Default; use std::hash::...
} impl Hasher for FnvHasher { type Output = u64; fn reset(&mut self) { *self = Default::default(); } fn finish(&self) -> u64 { self.0 } } impl Writer for FnvHasher { fn write(&mut self, bytes: &[u8]) { let FnvHasher(mut hash) = *self; for byte in bytes.iter() { hash = hash...
{ FnvHasher(0xcbf29ce484222325) }
identifier_body
fnv.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
//! This file stolen wholesale from rustc/src/librustc/util/nodemap.rs use std::default::Default; use std::hash::{Hasher, Writer}; /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn't quite as speedy as we /// want. In the compiler we're not reall...
* 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/. */
random_line_split
lib.rs
/// Main library module for merging coverage files. use std::collections::BTreeSet; use std::env; use std::str; extern crate clap; extern crate chrono; #[macro_use] extern crate error_chain; /// This crate's error-related code, generated by `error-chain`. mod errors { // Create the Error, ErrorKind, ResultExt, ...
(header: &bcf::header::HeaderView, field_type: &str) -> BTreeSet<String> { let mut result: BTreeSet<String> = BTreeSet::new(); for record in header.header_records() { match record { bcf::HeaderRecord::Format { key: _, values } => match values.get("Type") { Some(this_type) =>...
get_field_names
identifier_name
lib.rs
/// Main library module for merging coverage files. use std::collections::BTreeSet; use std::env; use std::str; extern crate clap; extern crate chrono; #[macro_use] extern crate error_chain; /// This crate's error-related code, generated by `error-chain`. mod errors { // Create the Error, ErrorKind, ResultExt, ...
else { let num_samples = reader.header(i).sample_count(); for _j in 0..num_samples { values_v.push(b"".to_vec()); } } } let values: Vec<&[u8]> = values_v .iter() .ma...
{ let mut rec_in = reader .record(i) .expect("We just checked that the record should be there!"); let mut tmp_v = rec_in .format(&key_b) .string() .unwrap_or_el...
conditional_block
lib.rs
/// Main library module for merging coverage files. use std::collections::BTreeSet; use std::env; use std::str; extern crate clap; extern crate chrono; #[macro_use] extern crate error_chain; /// This crate's error-related code, generated by `error-chain`. mod errors { // Create the Error, ErrorKind, ResultExt, ...
} assert!(first.is_some()); let record = first.as_mut().unwrap(); // Push GT, always no-call for coverage records. let values = (0..(1 * num_samples)) .map(|_| bcf::GT_MISSING) .collect::<Vec<i32>>(); record .push_format_integer(b"GT", v...
{ while reader .read_next() .chain_err(|| "Problem reading from input BCF files")? != 0 { // TODO: also merge INFO values? // Locate first record; will copy INFO from there; FORMAT comes later. let mut first: Option<bcf::Record> = None; let num_samples = w...
identifier_body
lib.rs
/// Main library module for merging coverage files. use std::collections::BTreeSet; use std::env; use std::str; extern crate clap; extern crate chrono; #[macro_use] extern crate error_chain; /// This crate's error-related code, generated by `error-chain`. mod errors { // Create the Error, ErrorKind, ResultExt, ...
.iter() .map(|v| v.as_slice()) .collect::<Vec<&[u8]>>(); record .push_format_string(key_b, values.as_slice()) .chain_err(|| format!("Could not write FORMAT/{}", key))?; } // Collect input FORMAT Float fields and push...
values_v.push(b"".to_vec()); } } } let values: Vec<&[u8]> = values_v
random_line_split
udev.rs
//! `udev` related functionality for automated device scanning //! //! This module mainly provides the [`UdevBackend`], which monitors available DRM devices and acts as //! an event source to be inserted in [`calloop`], generating events whenever these devices change. //! //! *Note:* Once inserted into the event loop, ...
/// ## Arguments /// `seat` - system seat which should be bound /// `logger` - slog Logger to be used by the backend and its `DrmDevices`. pub fn new<L, S: AsRef<str>>(seat: S, logger: L) -> IoResult<UdevBackend> where L: Into<Option<::slog::Logger>>, { let log = crate::slog_...
impl UdevBackend { /// Creates a new [`UdevBackend`] ///
random_line_split
udev.rs
//! `udev` related functionality for automated device scanning //! //! This module mainly provides the [`UdevBackend`], which monitors available DRM devices and acts as //! an event source to be inserted in [`calloop`], generating events whenever these devices change. //! //! *Note:* Once inserted into the event loop, ...
} /// Events generated by the [`UdevBackend`], notifying you of changes in system devices #[derive(Debug)] pub enum UdevEvent { /// A new device has been detected Added { /// ID of the new device device_id: dev_t, /// Path of the new device path: PathBuf, }, /// A devic...
{ self.token = Token::invalid(); poll.unregister(self.as_raw_fd()) }
identifier_body
udev.rs
//! `udev` related functionality for automated device scanning //! //! This module mainly provides the [`UdevBackend`], which monitors available DRM devices and acts as //! an event source to be inserted in [`calloop`], generating events whenever these devices change. //! //! *Note:* Once inserted into the event loop, ...
} } // New connector EventType::Change => { if let Some(devnum) = event.devnum() { info!(self.logger, "Device changed: #{}", devnum); if self.devices.contains_key(&devnum) { ...
{ callback(UdevEvent::Removed { device_id: devnum }, &mut ()); }
conditional_block
udev.rs
//! `udev` related functionality for automated device scanning //! //! This module mainly provides the [`UdevBackend`], which monitors available DRM devices and acts as //! an event source to be inserted in [`calloop`], generating events whenever these devices change. //! //! *Note:* Once inserted into the event loop, ...
(dev: dev_t) -> IoResult<Option<OsString>> { let mut enumerator = Enumerator::new()?; enumerator.match_subsystem("drm")?; enumerator.match_sysname("card[0-9]*")?; Ok(enumerator .scan_devices()? .filter(|device| device.devnum() == Some(dev)) .flat_map(|dev| { let mut devi...
driver
identifier_name
instr_extractps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn extractps_1() { run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Dir...
} #[test] fn extractps_4() { run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Indirect(RDX, Some(OperandSize::Dword), None)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(62)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None ...
} #[test] fn extractps_3() { run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Direct(EDI)), operand2: Some(Direct(XMM3)), operand3: Some(Literal8(85)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 23, 223, 85], Op...
random_line_split
instr_extractps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn extractps_1()
#[test] fn extractps_2() { run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(IndirectScaledDisplaced(EAX, Four, 630659303, Some(OperandSize::Dword), None)), operand2: Some(Direct(XMM7)), operand3: Some(Literal8(106)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: fal...
{ run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Direct(EBP)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(70)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 23, 245, 70], OperandSize::Dword) }
identifier_body
instr_extractps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::EXTRACTPS, operand1: Some(Direct(EBP)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(70)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 23, 245, 70], OperandSize::Dword) } #[te...
extractps_1
identifier_name
deriving-cmp-generic-enum.rs
// Copyright 2013 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 ...
#[derive(PartialEq, Eq, PartialOrd, Ord)] enum E<T> { E0, E1(T), E2(T,T) } pub fn main() { let e0 = E::E0; let e11 = E::E1(1i); let e12 = E::E1(2i); let e21 = E::E2(1i, 1i); let e22 = E::E2(1i, 2i); // in order for both PartialOrd and Ord let es = [e0, e11, e12, e21, e22]; ...
// no-pretty-expanded FIXME #15189
random_line_split
deriving-cmp-generic-enum.rs
// Copyright 2013 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 ...
// PartialEq assert_eq!(*e1 == *e2, eq); assert_eq!(*e1!= *e2,!eq); // PartialOrd assert_eq!(*e1 < *e2, lt); assert_eq!(*e1 > *e2, gt); assert_eq!(*e1 <= *e2, le); assert_eq!(*e1 >= *e2, ge); // Ord ...
{ let e0 = E::E0; let e11 = E::E1(1i); let e12 = E::E1(2i); let e21 = E::E2(1i, 1i); let e22 = E::E2(1i, 2i); // in order for both PartialOrd and Ord let es = [e0, e11, e12, e21, e22]; for (i, e1) in es.iter().enumerate() { for (j, e2) in es.iter().enumerate() { let...
identifier_body
deriving-cmp-generic-enum.rs
// Copyright 2013 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 ...
<T> { E0, E1(T), E2(T,T) } pub fn main() { let e0 = E::E0; let e11 = E::E1(1i); let e12 = E::E1(2i); let e21 = E::E2(1i, 1i); let e22 = E::E2(1i, 2i); // in order for both PartialOrd and Ord let es = [e0, e11, e12, e21, e22]; for (i, e1) in es.iter().enumerate() { ...
E
identifier_name
receipt.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
() { let expected = ::rustc_serialize::hex::FromHex::from_hex("f90162a02f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee83040caeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000...
test_basic
identifier_name
receipt.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
} impl Decodable for Receipt { fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); let receipt = Receipt { state_root: try!(d.val_at(0)), gas_used: try!(d.val_at(1)), log_bloom: try!(d.val_at(2)), logs: try!(d.val_at(3)), }; Ok(receipt) } } impl ...
{ s.begin_list(4); s.append(&self.state_root); s.append(&self.gas_used); s.append(&self.log_bloom); s.append(&self.logs); }
identifier_body
receipt.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
state_root: try!(d.val_at(0)), gas_used: try!(d.val_at(1)), log_bloom: try!(d.val_at(2)), logs: try!(d.val_at(3)), }; Ok(receipt) } } impl HeapSizeOf for Receipt { fn heap_size_of_children(&self) -> usize { self.logs.heap_size_of_children() } } /// Receipt with additional info. #[derive(Debug, Cl...
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder { let d = decoder.as_rlp(); let receipt = Receipt {
random_line_split
mod.rs
//! ===================================================================================== //! //! Filename: movement/mod.rs //! //! Description: Components to update actor's movement. //! //! Version: 1.0 //! Created: 13/06/16 22:43:05
//! //! Author: Anicka Burova //! //! ===================================================================================== extern crate rand; use rand::Rng; use collision::{Aabb}; use tcod::input::KeyCode; use component::Component; use util::{Offset}; use actor::Actor; use game::Game; use world::World; pu...
//! Revision: none //! Compiler: rust
random_line_split
mod.rs
//! ===================================================================================== //! //! Filename: movement/mod.rs //! //! Description: Components to update actor's movement. //! //! Version: 1.0 //! Created: 13/06/16 22:43:05 //! Revision: none //! Compiler: rust //! /...
} pub struct InputMovement; impl Component for InputMovement { fn update(&mut self, actor: &mut Actor, game: &Game, _: &mut World) { let mut offset = Offset::new(0,0); let key = game.last_key; match key { KeyCode::Up => offset.y = -1, KeyCode::Down =>...
{ let offset_x = rand::thread_rng().gen_range(-1,2); let new_pos = actor.position + Offset::new(offset_x, 0); let mut res = actor.position; if game.window_bounds.contains(new_pos) { res = new_pos; } let offset_y = rand::thread_rng().gen_range(-1,2); le...
identifier_body
mod.rs
//! ===================================================================================== //! //! Filename: movement/mod.rs //! //! Description: Components to update actor's movement. //! //! Version: 1.0 //! Created: 13/06/16 22:43:05 //! Revision: none //! Compiler: rust //! /...
; impl Component for InputMovement { fn update(&mut self, actor: &mut Actor, game: &Game, _: &mut World) { let mut offset = Offset::new(0,0); let key = game.last_key; match key { KeyCode::Up => offset.y = -1, KeyCode::Down => offset.y = 1, K...
InputMovement
identifier_name
mod.rs
//! ===================================================================================== //! //! Filename: movement/mod.rs //! //! Description: Components to update actor's movement. //! //! Version: 1.0 //! Created: 13/06/16 22:43:05 //! Revision: none //! Compiler: rust //! /...
actor.position = res; } } pub struct InputMovement; impl Component for InputMovement { fn update(&mut self, actor: &mut Actor, game: &Game, _: &mut World) { let mut offset = Offset::new(0,0); let key = game.last_key; match key { KeyCode::Up => offset.y = -1...
{ res = new_pos; }
conditional_block
api.rs
//! The Api system is responsible for talking to our Turtl server, and manages //! our user authentication. use ::std::io::Read; use ::std::time::Duration; use ::config; use ::reqwest::{Method, blocking::RequestBuilder, blocking::Client, Url, Proxy}; use ::reqwest::header::{HeaderMap, HeaderValue}; pub use ::reqwest::...
(&self, req: RequestBuilder) -> RequestBuilder { match self.config.auth.as_ref() { Some(x) => req.header("Authorization", x.clone()), None => req, } } /// Set our standard auth header into a Headers set fn set_standard_headers(&self, req: RequestBuilder) -> RequestBu...
set_auth_headers
identifier_name
api.rs
//! The Api system is responsible for talking to our Turtl server, and manages //! our user authentication. use ::std::io::Read; use ::std::time::Duration; use ::config; use ::reqwest::{Method, blocking::RequestBuilder, blocking::Client, Url, Proxy}; use ::reqwest::header::{HeaderMap, HeaderValue}; pub use ::reqwest::...
pub fn new() -> Api { Api { config: ApiConfig::new(), } } /// Set the API's authentication pub fn set_auth(&mut self, auth: String) -> MResult<()> { let auth_str = String::from("user:") + &auth; let base_auth = crypto::to_base64(&Vec::from(auth_str.as_bytes()...
impl Api { /// Create an Api
random_line_split
loader.rs
_library_crate() { Some(t) => t, None => { self.report_load_errs(); unreachable!() } } } pub fn report_load_errs(&mut self) { let message = if self.rejected_via_hash.len() > 0 { format!("found possibly newer version...
// store the data as a static buffer.
random_line_split
loader.rs
{ archive: ArchiveRO, // See comments in ArchiveMetadata::new for why this is static data: &'static [u8], } pub struct CratePaths { pub ident: String, pub dylib: Option<Path>, pub rlib: Option<Path> } impl CratePaths { fn paths(&self) -> Vec<Path> { match (&self.dylib, &self.rlib)...
ArchiveMetadata
identifier_name
loader.rs
(HashSet::new(), HashSet::new()) }); let (_, ref mut dylibs) = *slot; dylibs.insert(fs::realpath(path).unwrap()); FileMatches } None => { info!("dyl...
{ match get_metadata_section(os, path) { Ok(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out), Err(msg) => { write!(out, "{}\n", msg) } } }
identifier_body
signer.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Check if the given address is the signing address. pub fn is_address(&self, address: &Address) -> bool { *self.address.read() == *address } }
{ self.address.read().clone() }
identifier_body
signer.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self, ap: Arc<AccountProvider>, address: Address, password: String) { *self.account_provider.lock() = ap; *self.address.write() = address; *self.password.write() = Some(password); debug!(target: "poa", "Setting Engine signer to {}", address); } /// Sign a consensus message hash. pub fn sign(&self, hash: H...
set
identifier_name
signer.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn default() -> Self { EngineSigner { account_provider: Mutex::new(Arc::new(AccountProvider::transient_provider())), address: Default::default(), password: Default::default(), } } } impl EngineSigner { /// Set up the signer to sign with given address and password. pub fn set(&self, ap: Arc<AccountProv...
impl Default for EngineSigner {
random_line_split
credential.rs
use std::collections::HashMap; use ursa::cl::{ CredentialSignature, RevocationRegistry, SignatureCorrectnessProof, Witness }; use indy_api_types::validation::Validatable; use super::credential_definition::CredentialDefinitionId; use super::revocation_registry_definition::RevocationRegistryId; use sup...
(pub HashMap<String, AttributeValues>); #[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq)] pub struct AttributeValues { pub raw: String, pub encoded: String } impl Validatable for CredentialValues { fn validate(&self) -> Result<(), String> { if self.0.is_empty() { return Er...
CredentialValues
identifier_name
credential.rs
use std::collections::HashMap; use ursa::cl::{ CredentialSignature, RevocationRegistry, SignatureCorrectnessProof, Witness }; use indy_api_types::validation::Validatable; use super::credential_definition::CredentialDefinitionId; use super::revocation_registry_definition::RevocationRegistryId; use sup...
if self.values.0.is_empty() { return Err(String::from("Credential validation failed: `values` is empty")); } Ok(()) } }
{ return Err(String::from("Credential validation failed: `witness` and `rev_reg` must be passed for revocable Credential")); }
conditional_block
credential.rs
use std::collections::HashMap; use ursa::cl::{ CredentialSignature, RevocationRegistry, SignatureCorrectnessProof, Witness }; use indy_api_types::validation::Validatable; use super::credential_definition::CredentialDefinitionId; use super::revocation_registry_definition::RevocationRegistryId; use sup...
self.values.validate()?; if self.rev_reg_id.is_some() && (self.witness.is_none() || self.rev_reg.is_none()) { return Err(String::from("Credential validation failed: `witness` and `rev_reg` must be passed for revocable Credential")); } if self.values.0.is_empty() { ...
self.cred_def_id.validate()?;
random_line_split
hof.rs
#![feature(iter_arith)] fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2,... to infinity for n in 0.. { // Square the number let n_sq...
// Functional approach let sum_of_squared_odd_numbers: u32 = (0..).map(|n| n * n) // All natural numbers squared .take_while(|&n| n < upper) // Below upper limit .filter(|n| is_odd(*n)) // That are odd .sum(); // Sum them printl...
} println!("imperative style: {}", acc);
random_line_split
hof.rs
#![feature(iter_arith)] fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2,... to infinity for n in 0.. { // Square the number let n_sq...
} println!("imperative style: {}", acc); // Functional approach let sum_of_squared_odd_numbers: u32 = (0..).map(|n| n * n) // All natural numbers squared .take_while(|&n| n < upper) // Below upper limit .filter(|n| is_odd(*n)) // That are odd ...
{ // Accumulate value, if it's odd acc += n_squared; }
conditional_block
hof.rs
#![feature(iter_arith)] fn
() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2,... to infinity for n in 0.. { // Square the number let n_squared = n * n; if n_squ...
main
identifier_name
hof.rs
#![feature(iter_arith)] fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2,... to infinity for n in 0.. { // Square the number let n_sq...
{ n % 2 == 1 }
identifier_body
slice_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. /// SliceStack holds a non-guarded stack allocated elsewhere and provided as a mutable slice. /// /// Any slice used in a SliceStack mus...
#[inline(always)] fn limit(&self) -> *mut u8 { self.0.as_ptr() as *mut u8 } }
{ // The slice cannot wrap around the address space, so the conversion from usize // to isize will not wrap either. let len: isize = self.0.len() as isize; unsafe { self.limit().offset(len) } }
identifier_body
slice_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. /// SliceStack holds a non-guarded stack allocated elsewhere and provided as a mutable slice. /// /// Any slice used in a SliceStack mus...
(&self) -> *mut u8 { self.0.as_ptr() as *mut u8 } }
limit
identifier_name
slice_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. /// SliceStack holds a non-guarded stack allocated elsewhere and provided as a mutable slice. /// /// Any slice used in a SliceStack mus...
#[inline(always)] fn base(&self) -> *mut u8 { // The slice cannot wrap around the address space, so the conversion from usize // to isize will not wrap either. let len: isize = self.0.len() as isize; unsafe { self.limit().offset(len) } } #[inline(always)] fn limit(&s...
#[derive(Debug)] pub struct SliceStack<'a>(pub &'a mut [u8]); impl<'a> ::stack::Stack for SliceStack<'a> {
random_line_split
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn main() { env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("Ale...
; let server = coinched::server::http::Server::new(port); server.run(); }
{ 3000 }
conditional_block
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn
() { env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("Alexandre Bury <alexandre.bury@gmail.com>") .about("A coinche server") .arg(Arg::with_name("PORT") ...
main
identifier_name
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn main() { env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("Ale...
.short("p") .long("port") .takes_value(true)) .get_matches(); let port = if let Some(port) = matches.value_of("PORT") { match u16::from_str(port) { Ok(port) => port, Err(er...
.about("A coinche server") .arg(Arg::with_name("PORT") .help("Port to listen to (defaults to 3000)")
random_line_split
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn main()
} } } else { 3000 }; let server = coinched::server::http::Server::new(port); server.run(); }
{ env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("Alexandre Bury <alexandre.bury@gmail.com>") .about("A coinche server") .arg(Arg::with_name("PORT") ...
identifier_body
entry.rs
use consts::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Entry { pub cell: u8, pub num: u8, } impl Entry { #[inline] pub fn cell(self) -> usize { self.cell as usize } #[inline] pub fn row(self) -> u8 { self.cell as u8 / 9 } #[inline] pub fn col(self) -> u8 { self.cell as u8 % 9 } ...
#[inline] pub fn row_constraint(self) -> usize { self.row() as usize * 9 + self.num_offset() } #[inline] pub fn col_constraint(self) -> usize { self.col() as usize * 9 + self.num_offset() + COL_OFFSET } #[inline] pub fn field_constraint(self) -> usize { self.field() as usize * 9 + self.num_offset() + FIELD_...
{ self.num() as usize - 1 }
identifier_body
entry.rs
use consts::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Entry { pub cell: u8, pub num: u8, } impl Entry { #[inline] pub fn cell(self) -> usize { self.cell as usize } #[inline] pub fn row(self) -> u8 { self.cell as u8 / 9 } #[inline] pub fn col(self) -> u8 { self.cell as u8 % 9 } ...
0...80 => self.row_constraint(), 81...161 => self.col_constraint(), 162...242 => self.field_constraint(), 243...323 => self.cell_constraint(), _ => unreachable!(), } } }
#[inline] pub fn constrains(self, constraint_nr: usize) -> bool { constraint_nr == match constraint_nr {
random_line_split
entry.rs
use consts::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Entry { pub cell: u8, pub num: u8, } impl Entry { #[inline] pub fn
(self) -> usize { self.cell as usize } #[inline] pub fn row(self) -> u8 { self.cell as u8 / 9 } #[inline] pub fn col(self) -> u8 { self.cell as u8 % 9 } #[inline] pub fn field(self) -> u8 { self.row() / 3 * 3 + self.col() / 3 } #[inline] pub fn num(self) -> u8 { self.num } #[inline] pub fn conflicts_with(self, o...
cell
identifier_name
adv3.rs
#![allow(warnings)] // Goal #1: Eliminate the borrow check error in the `remove` method. pub struct Map<K: Eq, V> { elements: Vec<(K, V)>, } impl<K: Eq, V> Map<K, V> { pub fn new() -> Self { Map { elements: vec![] } } pub fn
(&mut self, key: K, value: V) { self.elements.push((key, value)); } pub fn get(&self, key: &K) -> Option<&V> { self.elements.iter().rev().find(|pair| pair.0 == *key).map(|pair| &pair.1) } pub fn remove(&mut self, key: &K) { let mut i : Option<usize> = None; for (index, pair...
insert
identifier_name
adv3.rs
#![allow(warnings)] // Goal #1: Eliminate the borrow check error in the `remove` method. pub struct Map<K: Eq, V> { elements: Vec<(K, V)>, } impl<K: Eq, V> Map<K, V> { pub fn new() -> Self { Map { elements: vec![] } } pub fn insert(&mut self, key: K, value: V) { self.elements.push((k...
, } } }
{}
conditional_block