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 |
|---|---|---|---|---|
popup_menu.rs | use std::cell::RefCell;
use std::cmp::min;
use std::iter;
use std::rc::Rc;
use gdk::{EventButton, EventType};
use glib;
use gtk;
use gtk::prelude::*;
use pango;
use neovim_lib::{Neovim, NeovimApi};
use crate::highlight::HighlightMap;
use crate::input;
use crate::nvim::{self, ErrorReport, NeovimClient};
use crate::re... | (&self, selected: i64) {
self.state.borrow().select(selected);
}
pub fn set_preview(&self, preview: bool) {
self.state.borrow_mut().set_preview(preview);
}
}
pub struct PopupMenuContext<'a> {
pub nvim: &'a Rc<NeovimClient>,
pub hl: &'a HighlightMap,
pub font_ctx: &'a render::Co... | select | identifier_name |
manager.rs | use {Metadata,Info,Id};
use ir;
use std;
/// The pass manager.
pub struct Manager
{
passes: Vec<Info>,
}
impl Manager
{
pub fn empty() -> Self {
Manager {
passes: Vec::new(),
}
}
/// Adds a pass to the manager.
pub fn add_pass<P>(mut self, pass: P) -> Self
wher... |
/// Runs the pass manager.
pub fn run(&mut self, mut module: ir::Module) -> ir::Module {
let pass_list = self::build_pass_list(&self.passes);
for pass_id in pass_list {
let pass = self::lookup_pass_mut(pass_id, &mut self.passes).unwrap();
match *pass {
... | } | random_line_split |
manager.rs | use {Metadata,Info,Id};
use ir;
use std;
/// The pass manager.
pub struct Manager
{
passes: Vec<Info>,
}
impl Manager
{
pub fn empty() -> Self {
Manager {
passes: Vec::new(),
}
}
/// Adds a pass to the manager.
pub fn add_pass<P>(mut self, pass: P) -> Self
wher... | (passes: &[Info]) -> Vec<Id> {
// FIXME: Take into account dependencies.
passes.iter().map(|p| p.id()).collect()
}
/// Finds a pass in an array based on ID.
fn lookup_pass_mut(id: Id, passes: &mut [Info])
-> Option<&mut Info> {
passes.iter_mut().find(|p| p.id() == id)
}
| build_pass_list | identifier_name |
manager.rs | use {Metadata,Info,Id};
use ir;
use std;
/// The pass manager.
pub struct Manager
{
passes: Vec<Info>,
}
impl Manager
{
pub fn empty() -> Self {
Manager {
passes: Vec::new(),
}
}
/// Adds a pass to the manager.
pub fn add_pass<P>(mut self, pass: P) -> Self
wher... | {
passes.iter_mut().find(|p| p.id() == id)
} | identifier_body | |
mod.rs | #![cfg(target_os="android")]
#![cfg(feature = "oculusvr")]
mod display;
mod gamepad;
mod service;
use {VRService, VRServiceCreator};
pub struct OculusVRServiceCreator;
impl OculusVRServiceCreator {
pub fn new() -> Box<OculusVRServiceCreator> {
Box::new(OculusVRServiceCreator)
}
}
impl VRServiceCrea... | } | pub use super::service::Java_com_rust_webvr_OVRService_nativeOnPause;
pub use super::service::Java_com_rust_webvr_OVRService_nativeOnResume;
pub use super::service::Java_com_rust_webvr_OVRService_nativeOnSurfaceChanged;
pub use super::service::Java_com_rust_webvr_OVRService_nativeOnSurfaceDestroyed; | random_line_split |
mod.rs | #![cfg(target_os="android")]
#![cfg(feature = "oculusvr")]
mod display;
mod gamepad;
mod service;
use {VRService, VRServiceCreator};
pub struct OculusVRServiceCreator;
impl OculusVRServiceCreator {
pub fn new() -> Box<OculusVRServiceCreator> |
}
impl VRServiceCreator for OculusVRServiceCreator {
fn new_service(&self) -> Box<VRService> {
Box::new(service::OculusVRService::new())
}
}
// Export functions called from Java
pub mod jni {
pub use super::service::Java_com_rust_webvr_OVRService_nativeOnPause;
pub use super::service::Java... | {
Box::new(OculusVRServiceCreator)
} | identifier_body |
mod.rs | #![cfg(target_os="android")]
#![cfg(feature = "oculusvr")]
mod display;
mod gamepad;
mod service;
use {VRService, VRServiceCreator};
pub struct | ;
impl OculusVRServiceCreator {
pub fn new() -> Box<OculusVRServiceCreator> {
Box::new(OculusVRServiceCreator)
}
}
impl VRServiceCreator for OculusVRServiceCreator {
fn new_service(&self) -> Box<VRService> {
Box::new(service::OculusVRService::new())
}
}
// Export functions called f... | OculusVRServiceCreator | identifier_name |
ext.rs | // Copyright 2014 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 AsRawSocket for net::TcpListener {
fn as_raw_socket(&self) -> Socket { *self.as_inner().socket().as_inner() }
}
impl AsRawSocket for net::UdpSocket {
fn as_raw_socket(&self) -> Socket { *self.as_inner().socket().as_inner() }
}
// Windows-specific extensions to `OsString`.
pub trait OsStringExt {
//... | { *self.as_inner().socket().as_inner() } | identifier_body |
ext.rs | // Copyright 2014 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 ... | /// will always return the original code units.
fn from_wide(wide: &[u16]) -> Self;
}
impl OsStringExt for OsString {
fn from_wide(wide: &[u16]) -> OsString {
FromInner::from_inner(Buf { inner: Wtf8Buf::from_wide(wide) })
}
}
// Windows-specific extensions to `OsStr`.
pub trait OsStrExt {
... | // Windows-specific extensions to `OsString`.
pub trait OsStringExt {
/// Create an `OsString` from a potentially ill-formed UTF-16 slice of 16-bit code units.
///
/// This is lossless: calling `.encode_wide()` on the resulting string | random_line_split |
ext.rs | // Copyright 2014 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) -> Handle {
self.as_inner().handle()
}
}
/// Extract raw sockets.
pub trait AsRawSocket {
fn as_raw_socket(&self) -> Socket;
}
#[allow(deprecated)]
impl AsRawSocket for old_io::net::tcp::TcpStream {
fn as_raw_socket(&self) -> Socket {
self.as_inner().fd()
}
}
#[allow(deprecate... | as_raw_handle | identifier_name |
lib.rs | //! Miscellaneous tools for concurrent programming.
//!
//! ## Atomics | //! * [`AtomicCell`], a thread-safe mutable memory location.
//! * [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.
//!
//! ## Thread synchronization
//!
//! * [`Parker`], a thread parking primitive.
//! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads.
//! *... | //! | random_line_split |
lib.rs | #![cfg_attr(feature = "no_std", no_std)]
#[macro_use]
extern crate cfg_if;
cfg_if! (
if #[cfg(feature="no_std")] {
use core::str::FromStr;
} else {
use std::str::FromStr;
}
);
mod char;
mod int;
pub use char::TryFromIntToCharError;
pub use int::TryFromIntError;
pub trait TryFrom<T>: Size... | (string: &'a str) -> Result<Self, Self::Err> {
T::from_str(string)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_have_try_from_impl_for_from_str() {
let result = u32::try_from("3");
assert_eq!(result.unwrap(), 3)
}
#[test]
fn should_have_try_from_imp... | try_from | identifier_name |
lib.rs | #![cfg_attr(feature = "no_std", no_std)]
#[macro_use]
extern crate cfg_if;
cfg_if! (
if #[cfg(feature="no_std")] {
use core::str::FromStr;
} else {
use std::str::FromStr;
}
);
mod char;
mod int;
pub use char::TryFromIntToCharError;
pub use int::TryFromIntError;
pub trait TryFrom<T>: Size... | fn should_have_try_into_impl_for_from_str() {
let result: Result<u32, _> = "3".try_into();
assert_eq!(result.unwrap(), 3)
}
}
/// Error type used when conversion is infallible.
/// The never type (`!`) will replace this when it is available in stable Rust.
#[derive(Debug, Eq, PartialEq)]
pub en... | "invalid digit found in string"
)
}
#[test] | random_line_split |
lib.rs | #![cfg_attr(feature = "no_std", no_std)]
#[macro_use]
extern crate cfg_if;
cfg_if! (
if #[cfg(feature="no_std")] {
use core::str::FromStr;
} else {
use std::str::FromStr;
}
);
mod char;
mod int;
pub use char::TryFromIntToCharError;
pub use int::TryFromIntError;
pub trait TryFrom<T>: Size... |
#[test]
fn should_have_try_into_impl_for_from_str() {
let result: Result<u32, _> = "3".try_into();
assert_eq!(result.unwrap(), 3)
}
}
/// Error type used when conversion is infallible.
/// The never type (`!`) will replace this when it is available in stable Rust.
#[derive(Debug, Eq, Part... | {
let result = u32::try_from("hello");
assert_eq!(
format!("{}", result.unwrap_err()),
"invalid digit found in string"
)
} | identifier_body |
doublets.rs | extern crate doublets;
use doublets::*;
#[test]
pub fn word_to_itself() {
assert_doublets(&vec!["head", "head"], "head", "head");
}
#[test]
pub fn head_to_tail() {
assert_doublets(&vec!["head", "heal", "teal", "tell", "tall", "tail"], "head", "tail");
}
#[test]
pub fn door_to_lock() {
assert_doublets(&v... |
#[test]
pub fn no_doublet_found() {
assert_eq!(None, doublets("ye", "freezer"));
}
fn assert_doublets(expected: &Vec<&str>, start: &str, end: &str) {
let expected_as_strings: Vec<String> = expected.iter().map(|x| x.to_string()).collect();
assert_eq!(Some(expected_as_strings), doublets(start, end));
} | {
assert_doublets(&vec!["wheat", "cheat", "cheap", "cheep", "creep", "creed", "breed", "bread"], "wheat", "bread");
} | identifier_body |
doublets.rs | extern crate doublets;
use doublets::*;
#[test]
pub fn word_to_itself() {
assert_doublets(&vec!["head", "head"], "head", "head");
}
#[test]
pub fn head_to_tail() {
assert_doublets(&vec!["head", "heal", "teal", "tell", "tall", "tail"], "head", "tail");
}
#[test]
pub fn door_to_lock() {
assert_doublets(&v... | assert_eq!(Some(expected_as_strings), doublets(start, end));
} | random_line_split | |
doublets.rs | extern crate doublets;
use doublets::*;
#[test]
pub fn | () {
assert_doublets(&vec!["head", "head"], "head", "head");
}
#[test]
pub fn head_to_tail() {
assert_doublets(&vec!["head", "heal", "teal", "tell", "tall", "tail"], "head", "tail");
}
#[test]
pub fn door_to_lock() {
assert_doublets(&vec!["door", "boor", "book", "look", "lock"], "door", "lock");
}
#[test... | word_to_itself | identifier_name |
rcu.rs | /*******************************************************************************
*
* kit/kernel/sync/rcu.rs
*
* vim:ft=rust:ts=4:sw=4:et:tw=80
*
* Copyright (C) 2015-2021, Devyn Cairns
* Redistribution of this file is permitted under the terms of the simplified
* BSD license. See LICENSE for more information.
... | assert_eq!(Arc::strong_count(&rcu.read()), 2);
assert_eq!(Arc::strong_count(&rcu.read()), 2);
assert_eq!(*rcu.read(), (5, 6));
let original = rcu.read();
let new = (7, 8).into();
assert!(rcu.update(&original, new).is_ok());
assert_eq!(Arc::strong_count(&original), 1);
assert_eq!(Arc:... | random_line_split | |
rcu.rs | /*******************************************************************************
*
* kit/kernel/sync/rcu.rs
*
* vim:ft=rust:ts=4:sw=4:et:tw=80
*
* Copyright (C) 2015-2021, Devyn Cairns
* Redistribution of this file is permitted under the terms of the simplified
* BSD license. See LICENSE for more information.
... | {
let rcu = Rcu::new((5usize, 6usize).into());
assert_eq!(Arc::strong_count(&rcu.read()), 2);
assert_eq!(Arc::strong_count(&rcu.read()), 2);
assert_eq!(*rcu.read(), (5, 6));
let original = rcu.read();
let new = (7, 8).into();
assert!(rcu.update(&original, new).is_ok());
assert_eq!(A... | identifier_body | |
rcu.rs | /*******************************************************************************
*
* kit/kernel/sync/rcu.rs
*
* vim:ft=rust:ts=4:sw=4:et:tw=80
*
* Copyright (C) 2015-2021, Devyn Cairns
* Redistribution of this file is permitted under the terms of the simplified
* BSD license. See LICENSE for more information.
... | (&self, value: Arc<T>) {
unsafe {
let old = self.state.swap(Arc::into_raw(value) as *mut T, AcqRel);
let old_arc = Arc::from_raw(old);
drop(old_arc);
}
}
pub fn update(
&self,
original: &Arc<T>,
value: Arc<T>,
) -> Result<(), Arc<T... | put | identifier_name |
rcu.rs | /*******************************************************************************
*
* kit/kernel/sync/rcu.rs
*
* vim:ft=rust:ts=4:sw=4:et:tw=80
*
* Copyright (C) 2015-2021, Devyn Cairns
* Redistribution of this file is permitted under the terms of the simplified
* BSD license. See LICENSE for more information.
... | else {
continue;
}
} else {
return None;
}
}
}
}
impl<T> From<Arc<T>> for Rcu<T> {
fn from(arc: Arc<T>) -> Rcu<T> {
Rcu::new(arc)
}
}
impl<T> From<T> for Rcu<T> {
fn from(value: T) -> Rcu<T> {
Rcu::ne... | {
return Some(new);
} | conditional_block |
issue-17546.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 ... |
fn newer() -> NoResult<foo::MyEnum, String> {
//~^ ERROR expected type, found variant `NoResult`
unimplemented!()
}
fn main() {
let _ = new();
}
| {
//~^ ERROR expected type, found variant `Result`
unimplemented!()
} | identifier_body |
issue-17546.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 ... | fn new() -> NoResult<MyEnum, String> {
//~^ ERROR expected type, found variant `NoResult`
unimplemented!()
}
}
mod bar {
use foo::MyEnum::Result;
use foo;
fn new() -> Result<foo::MyEnum, String> {
//~^ ERROR expected type, found variant `Result`
unimplemented!()
... | random_line_split | |
issue-17546.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 ... | () -> NoResult<MyEnum, String> {
//~^ ERROR expected type, found variant `NoResult`
unimplemented!()
}
}
mod bar {
use foo::MyEnum::Result;
use foo;
fn new() -> Result<foo::MyEnum, String> {
//~^ ERROR expected type, found variant `Result`
unimplemented!()
}
}
fn n... | new | identifier_name |
damping2.rs | extern crate nalgebra as na;
use std::f32;
use na::{Point2, RealField, Vector2};
use ncollide2d::shape::{Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::math::Velocity;
use nphysics2d::object::{
BodyPartHandle, Coll... | mechanical_world,
geometrical_world,
bodies,
colliders,
joint_constraints,
force_generators,
);
testbed.look_at(Point2::new(3.0, 2.0), 75.0);
}
fn main() {
let testbed = Testbed::<f32>::from_builders(0, vec![("Damping", init_world)]);
testbed.run()
} | testbed.set_world( | random_line_split |
damping2.rs | extern crate nalgebra as na;
use std::f32;
use na::{Point2, RealField, Vector2};
use ncollide2d::shape::{Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::math::Velocity;
use nphysics2d::object::{
BodyPartHandle, Coll... | {
let testbed = Testbed::<f32>::from_builders(0, vec![("Damping", init_world)]);
testbed.run()
} | identifier_body | |
damping2.rs | extern crate nalgebra as na;
use std::f32;
use na::{Point2, RealField, Vector2};
use ncollide2d::shape::{Cuboid, ShapeHandle};
use nphysics2d::force_generator::DefaultForceGeneratorSet;
use nphysics2d::joint::DefaultJointConstraintSet;
use nphysics2d::math::Velocity;
use nphysics2d::object::{
BodyPartHandle, Coll... | <N: RealField>(testbed: &mut Testbed<N>) {
/*
* World
*/
let mechanical_world = DefaultMechanicalWorld::new(na::zero());
let geometrical_world = DefaultGeometricalWorld::new();
let mut bodies = DefaultBodySet::new();
let mut colliders = DefaultColliderSet::new();
let joint_constraints ... | init_world | identifier_name |
condition_1.rs | fn main() {
let n = 5i32;
if n < 0 {
print!("{} is negative", n);
} else if n > 0 {
print!("{} is positive", n);
} else {
print!("{} is zero", n);
}
let big_n =
if n < 10 && n > -10 {
println!(", and is a small number, increase ten-fold"... | // TODO ^ Try suppressing this expression with a semicolon
};
// ^ Don't forget to put a semicolon here! All the `let` bindings need it
println!("{} -> {}", n, big_n);
} |
// This expression must return an `int` as well
n / 2
| random_line_split |
tests.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | }
#[tokio::test]
async fn delete() -> Result<()> {
let mut rng = new_rng();
let chunks = Chunks::gen(&mut rng)?;
let root = temp_dir()?;
let mut chunk_store = ChunkStore::new(root.path(), u64::MAX).await?;
for (index, (data, size)) in chunks.data_and_sizes.iter().enumerate() {
let the_da... | {
let mut rng = new_rng();
let root = temp_dir()?;
let capacity = 32;
let mut chunk_store = ChunkStore::new(root.path(), capacity).await?;
let data = Data {
id: Id(rng.gen()),
value: rng
.sample_iter(&Standard)
.take((capacity + 1) as usize)
.coll... | identifier_body |
tests.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | () -> Result<()> {
let mut rng = new_rng();
let chunks = Chunks::gen(&mut rng)?;
let root = temp_dir()?;
let mut chunk_store = ChunkStore::new(root.path(), u64::MAX).await?;
for (index, (data, _)) in chunks.data_and_sizes.iter().enumerate() {
let id = Id(index as u64);
assert!(!chu... | keys | identifier_name |
tests.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | .await?;
let keys = chunk_store.keys();
assert!(keys.contains(&id));
assert_eq!(keys.len(), index + 1);
}
for (index, _) in chunks.data_and_sizes.iter().enumerate() {
let id = Id(index as u64);
assert!(chunk_store.keys().contains(&id));
chunk_store.d... | random_line_split | |
director.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/director.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A state stack that propogates update
and render signals.
*/
use std::local... | (&mut self)
{ }
/* Each state must have a unique key that other
* objects can use to reference it. */
fn get_key(&self) -> &str;
/* Returns true when the event has been captured. If the event is not
captured, it's set to the next lower state. (A state can capture
renders, for example, as an op... | unload | identifier_name |
director.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/director.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A state stack that propogates update
and render signals.
*/
use std::local... | }
do Director::get_mut |director|
{ director.run_deferreds(); }
}
pub fn key_char(ch: char)
{
let mut states = do Director::get |director|
{ do director.states.map |x| { *x } };
log_assert!(states.len() > 0);
for x in states.mut_rev_iter()
{
if x.key_char(ch)
{ break... |
for x in states.mut_rev_iter()
{
if x.key_action(key, action, mods)
{ break; } | random_line_split |
director.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/director.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A state stack that propogates update
and render signals.
*/
use std::local... |
pub fn render()
{
let mut states = do Director::get |director|
{ do director.states.map |x| { *x } };
log_assert!(states.len() > 0);
for x in states.mut_iter()
{
if x.render()
{ break; }
}
do Director::get_mut |director|
{ director.run_deferreds(); }
}
/** Input ... | {
let mut states = do Director::get |director|
{ do director.states.map |x| { *x } };
log_assert!(states.len() > 0);
for x in states.mut_iter()
{
if x.update(delta)
{ break; }
}
do Director::get_mut |director|
{ director.run_deferreds(); }
} | identifier_body |
director.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/state/director.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A state stack that propogates update
and render signals.
*/
use std::local... |
}
do Director::get_mut |director|
{ director.run_deferreds(); }
}
pub fn mouse_action(button: i32, action: i32, mods: i32)
{
let mut states = do Director::get |director|
{ do director.states.map |x| { *x } };
log_assert!(states.len() > 0);
for x in states.mut_rev_iter()
{
... | { break; } | conditional_block |
bytes.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 bytes = Bytes("0123456789abcdef".from_hex().unwrap());
let serialized = serde_json::to_string(&bytes).unwrap();
assert_eq!(serialized, r#""0x0123456789abcdef""#);
}
} | fn test_bytes_serialize() { | random_line_split |
bytes.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.... | (pub Vec<u8>);
impl Bytes {
/// Simple constructor.
pub fn new(bytes: Vec<u8>) -> Bytes {
Bytes(bytes)
}
pub fn to_vec(self) -> Vec<u8> { let Bytes(x) = self; x }
}
impl Serialize for Bytes {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer {
let mut serialized = "0x".t... | Bytes | identifier_name |
bytes.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 visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
use rustc_serialize::hex::FromHex;
#[test]
fn test_bytes_serialize() {
let bytes = Bytes("0123456789abcdef".from_hex().unwr... | {
Err(Error::custom("invalid hex"))
} | conditional_block |
runtime.rs | use crate::{
ast::AST,
compiler::compile_single,
errors::Error,
parser::{parse, ParseError},
values::RcValue,
vm::VM,
};
use std::{fs, path::Path};
pub struct Runtime {
vm: VM,
}
impl Runtime {
pub fn new() -> Runtime {
Runtime { vm: VM::new() }
}
pub fn parse_str<'a>(... |
match self.eval_str(&content) {
Ok(_) => (),
Err(e) => eprintln!("{:?}", e),
}
}
pub fn dump_heap(&self) {
self.vm.memory.dump();
}
} | random_line_split | |
runtime.rs | use crate::{
ast::AST,
compiler::compile_single,
errors::Error,
parser::{parse, ParseError},
values::RcValue,
vm::VM,
};
use std::{fs, path::Path};
pub struct Runtime {
vm: VM,
}
impl Runtime {
pub fn new() -> Runtime {
Runtime { vm: VM::new() }
}
pub fn parse_str<'a>(... |
};
match self.eval_str(&content) {
Ok(_) => (),
Err(e) => eprintln!("{:?}", e),
}
}
pub fn dump_heap(&self) {
self.vm.memory.dump();
}
}
| {
eprintln!("Failed loading {:?}: {:?}", path, e);
return;
} | conditional_block |
runtime.rs | use crate::{
ast::AST,
compiler::compile_single,
errors::Error,
parser::{parse, ParseError},
values::RcValue,
vm::VM,
};
use std::{fs, path::Path};
pub struct Runtime {
vm: VM,
}
impl Runtime {
pub fn new() -> Runtime {
Runtime { vm: VM::new() }
}
pub fn parse_str<'a>(... |
pub fn eval_file(&mut self, path: &Path) {
let content = match fs::read_to_string(path) {
Ok(content) => content,
Err(e) => {
eprintln!("Failed loading {:?}: {:?}", path, e);
return;
}
};
match self.eval_str(&content) {
... | {
let exprs = self.parse_str(input)?;
let mut evalued_exprs = Vec::new();
for expr in &exprs {
let bytecode = compile_single(expr)?;
let evalued_expr = self.vm.execute(bytecode)?;
evalued_exprs.push(evalued_expr);
}
Ok(evalued_exprs)
} | identifier_body |
runtime.rs | use crate::{
ast::AST,
compiler::compile_single,
errors::Error,
parser::{parse, ParseError},
values::RcValue,
vm::VM,
};
use std::{fs, path::Path};
pub struct Runtime {
vm: VM,
}
impl Runtime {
pub fn new() -> Runtime {
Runtime { vm: VM::new() }
}
pub fn parse_str<'a>(... | (&self) {
self.vm.memory.dump();
}
}
| dump_heap | identifier_name |
auto-ref-sliceable.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 ... | () {
let mut v = ~[1];
v.push_val(2);
v.push_val(3);
assert!(v == ~[1, 2, 3]);
}
| main | identifier_name |
auto-ref-sliceable.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 ... | assert!(v == ~[1, 2, 3]);
} | random_line_split | |
auto-ref-sliceable.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 ... |
}
pub fn main() {
let mut v = ~[1];
v.push_val(2);
v.push_val(3);
assert!(v == ~[1, 2, 3]);
}
| {
self.push(t);
} | identifier_body |
borrowck-univariant-enum.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 ... | {
newvar(int)
}
pub fn main() {
// Test that borrowck treats enums with a single variant
// specially.
let x = box(GC) Cell::new(5);
let y = box(GC) Cell::new(newvar(3));
let z = match y.get() {
newvar(b) => {
x.set(x.get() + 1);
x.get() * b
}
};
assert_eq... | newtype | identifier_name |
borrowck-univariant-enum.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.
// | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::Cell;
use std::gc::GC;
enum newtype {
newvar(int)
}
pub fn main() {
// Test that borrowck treats enums with a single variant
... | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
borrowck-univariant-enum.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 ... | {
// Test that borrowck treats enums with a single variant
// specially.
let x = box(GC) Cell::new(5);
let y = box(GC) Cell::new(newvar(3));
let z = match y.get() {
newvar(b) => {
x.set(x.get() + 1);
x.get() * b
}
};
assert_eq!(z, 18);
} | identifier_body | |
lib.rs | // Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.
#![crate_name="allegro_dialog_sys"]
#![crate_type = "lib"]
extern crate allegro_sys;
#[macro_use]
extern crate allegro_util;
extern crate libc;
pub use allegro_dialog::*;
pub mod allegro_dialog... | pub fn al_create_native_file_dialog(initial_path: *const c_char, title: *const c_char, patterns: *const c_char, mode: c_int) -> *mut ALLEGRO_FILECHOOSER;
pub fn al_show_native_file_dialog(display: *mut ALLEGRO_DISPLAY, dialog: *mut ALLEGRO_FILECHOOSER) -> c_bool;
pub fn al_get_native_file_dialog_count(dialog: *co... | extern "C"
{
pub fn al_init_native_dialog_addon() -> c_bool;
pub fn al_shutdown_native_dialog_addon(); | random_line_split |
htmliframeelement.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 dom::attr::Attr;
use dom::attr::AttrValue;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::H... |
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => (),
}
if tree_in_doc {
self.process_the_iframe_attributes();
}
}
}
| {
match self.super_type() {
Some(ref s) => s.before_remove_attr(attr),
_ => ()
}
match attr.local_name() {
&atom!("sandbox") => self.sandbox.set(None),
_ => ()
}
} | identifier_body |
htmliframeelement.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 dom::attr::Attr;
use dom::attr::AttrValue;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::H... | match name {
&atom!("sandbox") => AttrValue::from_serialized_tokenlist(value),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn before_remove_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.before_... | fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { | random_line_split |
htmliframeelement.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 dom::attr::Attr;
use dom::attr::AttrValue;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::H... | (self) -> Option<Temporary<Window>> {
self.subpage_id.get().and_then(|subpage_id| {
let window = window_from_node(self).root();
let window = window.r();
let children = window.page().children.borrow();
children.iter().find(|page| {
let window = page... | GetContentWindow | identifier_name |
euclidean.rs | // Using structs to represent 2D points
// and calculating the Euclidean distance between them
mod pointutils {
use std::num::pow;
pub struct Point {
pub x: f64,
pub y: f64,
}
pub fn | (point_a: Point, point_b: Point) -> f64 {
let value_sq = pow((point_a.x - point_b.x), 2) + pow((point_a.y - point_b.y), 2);
value_sq.sqrt()
}
}
fn main() {
let point_a: pointutils::Point = pointutils::Point { x: 0.3, y: 20.0 };
let point_b: pointutils::Point = pointutils::Point { x: 4.0, y:... | euclidean | identifier_name |
euclidean.rs | // Using structs to represent 2D points
// and calculating the Euclidean distance between them
mod pointutils {
use std::num::pow;
pub struct Point {
pub x: f64,
pub y: f64,
}
pub fn euclidean(point_a: Point, point_b: Point) -> f64 {
let value_sq = pow((point_a.x - point_b.x)... | let point_b: pointutils::Point = pointutils::Point { x: 4.0, y: -0.03 };
let euclidean_distance = pointutils::euclidean(point_a, point_b);
println!("Found distance: {}", euclidean_distance);
} | }
}
fn main() {
let point_a: pointutils::Point = pointutils::Point { x: 0.3, y: 20.0 }; | random_line_split |
euclidean.rs | // Using structs to represent 2D points
// and calculating the Euclidean distance between them
mod pointutils {
use std::num::pow;
pub struct Point {
pub x: f64,
pub y: f64,
}
pub fn euclidean(point_a: Point, point_b: Point) -> f64 |
}
fn main() {
let point_a: pointutils::Point = pointutils::Point { x: 0.3, y: 20.0 };
let point_b: pointutils::Point = pointutils::Point { x: 4.0, y: -0.03 };
let euclidean_distance = pointutils::euclidean(point_a, point_b);
println!("Found distance: {}", euclidean_distance);
}
| {
let value_sq = pow((point_a.x - point_b.x), 2) + pow((point_a.y - point_b.y), 2);
value_sq.sqrt()
} | identifier_body |
powerinfo.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Basic battery i... | Battery,
/// An external power source, a UPS.
UPS,
/// An unknown power source. (This should never happen.)
Unknown,
}
/// Information about how the machine is powered.
pub trait PowerInfo {
/// What source is the computer currently powered by.
///
/// ```rust
/// use hostinfo::{Hos... | pub enum PowerSource {
/// An external unlimited power source.
AC,
/// An internal battery power source. | random_line_split |
powerinfo.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Basic battery i... | {
/// Is the battery currently charging?
pub charging: bool,
/// The current capacity of the battery, as a percentage,
/// scaled to a value between `0.0` and `1.0`.
pub level: f64,
}
/// What is the power source for the machine?
///
/// This is obtained by calling `power_source` on a `HostInfo`:
... | BatteryInfo | identifier_name |
fsync.rs | use regex::Regex;
use std::cmp::{Eq, PartialEq};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::string::String;
use std::sync::Arc;
use unicode_casefold::UnicodeCaseFold;
use walkdir::{DirEntry, WalkDir};
pub struct MediaFile {
pub path: PathBuf,
base:... | )
.id()
);
// test strip tabs
assert_eq!(
"the end/something.mp3",
MediaFile::new("Music/The\tEnd/Something.mp3", base).id()
);
} | random_line_split | |
fsync.rs | use regex::Regex;
use std::cmp::{Eq, PartialEq};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::string::String;
use std::sync::Arc;
use unicode_casefold::UnicodeCaseFold;
use walkdir::{DirEntry, WalkDir};
pub struct MediaFile {
pub path: PathBuf,
base:... | .id()
);
// test strip tabs
assert_eq!(
"the end/something.mp3",
MediaFile::new("Music/The\tEnd/Something.mp3", base).id()
);
}
| {
let base = Path::new("Music");
// test bounce to lowercase
assert_eq!(
"andrew w. k./i get wet/02 - party hard.mp3",
MediaFile::new("Music/Andrew W. K./I Get Wet/02 - Party Hard.mp3", base).id()
);
// test supported ascii characters
assert_eq!(
"mêlée/everyday behavior... | identifier_body |
fsync.rs | use regex::Regex;
use std::cmp::{Eq, PartialEq};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::string::String;
use std::sync::Arc;
use unicode_casefold::UnicodeCaseFold;
use walkdir::{DirEntry, WalkDir};
pub struct | {
pub path: PathBuf,
base: Arc<PathBuf>,
}
static SPACE_CHARS: &'static [char] = &['\t'];
static DELETE_CHARS: &'static [char] = &[':'];
impl MediaFile {
pub fn new<P1, P2>(path: P1, base: P2) -> MediaFile
where
P1: Into<PathBuf>,
P2: Into<PathBuf>,
{
MediaFile {
... | MediaFile | identifier_name |
all.rs | #![deny(warnings)]
#![feature(io, path_ext, convert)]
extern crate cargo_registry;
extern crate conduit_middleware;
extern crate conduit_test;
extern crate rustc_serialize;
extern crate conduit;
extern crate curl;
extern crate git2;
extern crate time;
extern crate url;
extern crate semver;
use std::collections::HashM... |
fn mock_crate_vers(req: &mut Request, krate: Crate, v: &semver::Version)
-> (Crate, Version) {
let user = req.extensions().find::<User>().unwrap();
let mut krate = Crate::find_or_insert(req.tx().unwrap(), &krate.name,
user.id, &krate.description,
... | {
mock_crate_vers(req, krate, &semver::Version::parse("1.0.0").unwrap())
} | identifier_body |
all.rs | #![deny(warnings)]
#![feature(io, path_ext, convert)]
extern crate cargo_registry;
extern crate conduit_middleware;
extern crate conduit_test;
extern crate rustc_serialize;
extern crate conduit;
extern crate curl;
extern crate git2;
extern crate time;
extern crate url;
extern crate semver;
use std::collections::HashM... | let user = req.extensions().find::<User>().unwrap();
let mut krate = Crate::find_or_insert(req.tx().unwrap(), &krate.name,
user.id, &krate.description,
&krate.homepage,
&krate.documentation,
... | }
fn mock_crate_vers(req: &mut Request, krate: Crate, v: &semver::Version)
-> (Crate, Version) { | random_line_split |
all.rs | #![deny(warnings)]
#![feature(io, path_ext, convert)]
extern crate cargo_registry;
extern crate conduit_middleware;
extern crate conduit_test;
extern crate rustc_serialize;
extern crate conduit;
extern crate curl;
extern crate git2;
extern crate time;
extern crate url;
extern crate semver;
use std::collections::HashM... | (req: &mut Request, name: &str) -> Keyword {
Keyword::find_or_insert(req.tx().unwrap(), name).unwrap()
}
fn logout(req: &mut Request) {
req.mut_extensions().pop::<User>();
}
| mock_keyword | identifier_name |
state.rs | //! Stuff that uses the global state.
use crate::{atlas_cache::AtlasCache, Flick, FontData, ImageData, ImageKey};
use lazy_static::lazy_static;
use std::sync::Mutex;
#[derive(Default)]
pub struct EngineState {
pub atlas_cache: AtlasCache<String>,
pub average_frame_duration: Flick,
}
lazy_static! {
/// Glo... | /// image edges. Background color is the color of the bottom right corner pixel of the image. The
/// bounding boxes are returned lexically sorted by the coordinates of their bottom right corners,
/// first along the y-axis then along the x-axis. This produces a natural left-to-right,
/// bottom-to-top ordering for a c... |
/// Add a tilesheet image that gets automatically split to subimages based on image structure.
///
/// Tiles are bounding boxes of non-background pixel groups surrounded by only background pixels or | random_line_split |
state.rs | //! Stuff that uses the global state.
use crate::{atlas_cache::AtlasCache, Flick, FontData, ImageData, ImageKey};
use lazy_static::lazy_static;
use std::sync::Mutex;
#[derive(Default)]
pub struct EngineState {
pub atlas_cache: AtlasCache<String>,
pub average_frame_duration: Flick,
}
lazy_static! {
/// Glo... | (
id: impl Into<String>,
sheet: impl Into<image::RgbaImage>,
span: impl IntoIterator<Item = char>,
) -> FontData {
ENGINE_STATE
.lock()
.unwrap()
.atlas_cache
.add_tilesheet_font(id, sheet, span)
}
/// Get a drawable (sub)image from the cache corresponding to the given `Imag... | add_tilesheet_font | identifier_name |
state.rs | //! Stuff that uses the global state.
use crate::{atlas_cache::AtlasCache, Flick, FontData, ImageData, ImageKey};
use lazy_static::lazy_static;
use std::sync::Mutex;
#[derive(Default)]
pub struct EngineState {
pub atlas_cache: AtlasCache<String>,
pub average_frame_duration: Flick,
}
lazy_static! {
/// Glo... |
/// Add a tilesheet image that gets automatically split to subimages based on image structure.
///
/// Tiles are bounding boxes of non-background pixel groups surrounded by only background pixels or
/// image edges. Background color is the color of the bottom right corner pixel of the image. The
/// bounding boxes ar... | {
ENGINE_STATE
.lock()
.unwrap()
.atlas_cache
.add_sheet(id, sheet)
} | identifier_body |
hashstat.rs | //! A file structure for holding hash and "stat" information about
//! files. This is what fac uses to determine if a file has changed.
#[cfg(test)]
extern crate quickcheck;
use std;
use std::io::{Read};
use std::hash::{Hasher};
use metrohash::MetroHash64;
#[cfg(unix)]
use std::os::unix::fs::{MetadataExt};
use cra... |
/// stat a file
#[cfg(not(unix))]
pub fn stat(f: &std::path::Path) -> std::io::Result<HashStat> {
let s = std::fs::symlink_metadata(f)?;
Ok(HashStat {
time: 0,
time_ns: 0,
size: s.len() as u32,
hash: 0,
kind: kind_of(&s),
})
}
/// stat a file
#[cfg(unix)]
pub fn sta... | {
if m.file_type().is_symlink() {
Some(FileKind::Symlink)
} else if m.file_type().is_dir() {
Some(FileKind::Dir)
} else if m.file_type().is_file() {
Some(FileKind::File)
} else {
None
}
} | identifier_body |
hashstat.rs | //! A file structure for holding hash and "stat" information about
//! files. This is what fac uses to determine if a file has changed.
#[cfg(test)]
extern crate quickcheck;
use std;
use std::io::{Read};
use std::hash::{Hasher};
use metrohash::MetroHash64;
#[cfg(unix)]
use std::os::unix::fs::{MetadataExt};
use cra... | let mut out = 0;
for x in 0..16 {
let hexit = if i[x] < b'a' {
i[x] - b'0'
} else {
10 + i[x] - b'a'
};
out += (hexit as u64) << (x*4);
}
out
}
impl HashStat {
/// encode as bytes
pub fn encode(&self) -> Vec<u8> {
let mut v = Vec::... | }
// fn decode(i: &[u8; 16]) -> u64 {
fn decode(i: &[u8]) -> u64 { | random_line_split |
hashstat.rs | //! A file structure for holding hash and "stat" information about
//! files. This is what fac uses to determine if a file has changed.
#[cfg(test)]
extern crate quickcheck;
use std;
use std::io::{Read};
use std::hash::{Hasher};
use metrohash::MetroHash64;
#[cfg(unix)]
use std::os::unix::fs::{MetadataExt};
use cra... | (b: &OsStr) -> &[u8] {
b.to_str().unwrap().as_bytes()
}
| osstr_to_bytes | identifier_name |
hashstat.rs | //! A file structure for holding hash and "stat" information about
//! files. This is what fac uses to determine if a file has changed.
#[cfg(test)]
extern crate quickcheck;
use std;
use std::io::{Read};
use std::hash::{Hasher};
use metrohash::MetroHash64;
#[cfg(unix)]
use std::os::unix::fs::{MetadataExt};
use cra... |
if self.hash == 0 {
self.finish(f).unwrap();
}
self.hash == other.hash
}
/// see if it we know matches without doing any disk IO
pub fn cheap_matches(&mut self, other: &HashStat) -> bool {
if self.size == 0 {
return false;
}
self.size ... | {
return true;
} | conditional_block |
bubble_sort.rs | fn bubble_sort(v: &Vec<i32>) -> Vec<i32> {
let mut a = v.clone();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..(v.len()) {
if a[i - 1] > a[i] {
let aux = a[i];
a[i] = a[i - 1];
a[i - 1] = aux;
... | () {
assert_eq!(
bubble_sort(&vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]),
vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232]
);
}
| test | identifier_name |
bubble_sort.rs | fn bubble_sort(v: &Vec<i32>) -> Vec<i32> {
let mut a = v.clone();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..(v.len()) {
if a[i - 1] > a[i] {
let aux = a[i];
a[i] = a[i - 1];
a[i - 1] = aux;
... |
#[test]
fn test() {
assert_eq!(
bubble_sort(&vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]),
vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232]
);
}
| {
let a = vec![
1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100,
4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999,
];
let b = bubble_sort(&a);
println!("{:?}", b);
} | identifier_body |
bubble_sort.rs | fn bubble_sort(v: &Vec<i32>) -> Vec<i32> {
let mut a = v.clone();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..(v.len()) {
if a[i - 1] > a[i] |
}
}
a
}
fn main() {
let a = vec![
1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100,
4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999,
];
let b = bubble_sort(&a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
bubble_sort(&vec![1, 5, 65, 23, 57, 1232, -1, -5... | {
let aux = a[i];
a[i] = a[i - 1];
a[i - 1] = aux;
swapped = true;
} | conditional_block |
bubble_sort.rs | fn bubble_sort(v: &Vec<i32>) -> Vec<i32> {
let mut a = v.clone();
let mut swapped = true;
while swapped {
swapped = false;
for i in 1..(v.len()) {
if a[i - 1] > a[i] {
let aux = a[i];
a[i] = a[i - 1];
a[i - 1] = aux;
... | fn main() {
let a = vec![
1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100,
4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999,
];
let b = bubble_sort(&a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
bubble_sort(&vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2,... | }
}
a
}
| random_line_split |
main.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate librespot;
extern crate tokio_core;
extern crate tokio_signal;
use env_logger::LogBuilder;
use futures::{Future, Async, Poll, Stream};
use std::env;
use std::io::{self, stderr, Write};
use std::path::PathBu... | let name = self.config.name.clone();
let device_id = self.config.device_id.clone();
self.discovery = Some(discovery(&self.handle, name, device_id).unwrap());
}
fn credentials(&mut self, credentials: Credentials) {
let config = self.config.clone();
let handle = self.handl... |
fn discovery(&mut self) { | random_line_split |
main.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate librespot;
extern crate tokio_core;
extern crate tokio_signal;
use env_logger::LogBuilder;
use futures::{Future, Async, Poll, Stream};
use std::env;
use std::io::{self, stderr, Write};
use std::path::PathBu... | {
backend: fn(Option<String>) -> Box<Sink>,
device: Option<String>,
mixer: fn() -> Box<Mixer>,
cache: Option<Cache>,
config: Config,
credentials: Option<Credentials>,
enable_discovery: bool,
}
fn setup(args: &[String]) -> Setup {
let mut opts = getopts::Options::new();
opts.optop... | Setup | identifier_name |
main.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate librespot;
extern crate tokio_core;
extern crate tokio_signal;
use env_logger::LogBuilder;
use futures::{Future, Async, Poll, Stream};
use std::env;
use std::io::{self, stderr, Write};
use std::path::PathBu... |
builder.init().unwrap();
}
}
}
fn list_backends() {
println!("Available Backends : ");
for (&(name, _), idx) in BACKENDS.iter().zip(0..) {
if idx == 0 {
println!("- {} (default)", name);
} else {
println!("- {}", name);
}
}
}
#[deriv... | {
builder.parse("mdns=info,librespot=info");
} | conditional_block |
main.rs | #[macro_use] extern crate log;
extern crate env_logger;
extern crate futures;
extern crate getopts;
extern crate librespot;
extern crate tokio_core;
extern crate tokio_signal;
use env_logger::LogBuilder;
use futures::{Future, Async, Poll, Stream};
use std::env;
use std::io::{self, stderr, Write};
use std::path::PathBu... | }
};
let verbose = matches.opt_present("verbose");
setup_logging(verbose);
info!("librespot {} ({}). Built on {}.",
version::short_sha(),
version::commit_date(),
version::short_now());
let backend_name = matches.opt_str("backend");
if backend_nam... | {
let mut opts = getopts::Options::new();
opts.optopt("c", "cache", "Path to a directory where files will be cached.", "CACHE")
.reqopt("n", "name", "Device name", "NAME")
.optopt("b", "bitrate", "Bitrate (96, 160 or 320). Defaults to 160", "BITRATE")
.optopt("", "onstart", "Run PROGRAM ... | identifier_body |
issue-447.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod mozilla {
#[allow(unused_imports)]
use self::sup... | JSAutoCompartment_JSAutoCompartment(
__bindgen_tmp.as_mut_ptr(),
arg1,
);
__bindgen_tmp.assume_init()
}
}
} | let mut __bindgen_tmp = ::std::mem::MaybeUninit::uninit(); | random_line_split |
issue-447.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
pub mod root {
#[allow(unused_imports)]
use self::super::root;
pub mod mozilla {
#[allow(unused_imports)]
use self::sup... | () {
assert_eq!(
::std::mem::size_of::<JSAutoCompartment>(),
1usize,
concat!("Size of: ", stringify!(JSAutoCompartment))
);
assert_eq!(
::std::mem::align_of::<JSAutoCompartment>(),
1usize,
concat!("Alignment of ", stringify!... | bindgen_test_layout_JSAutoCompartment | identifier_name |
stack_overflow.rs | // Copyright 2014 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 Drop for Handler {
fn drop(&mut self) {}
}
// This is initialized in init() and only read from after
static mut PAGE_SIZE: usize = 0;
#[no_stack_check]
extern "system" fn vectored_handler(ExceptionInfo: *mut EXCEPTION_POINTERS) -> LONG {
unsafe {
let rec = &(*(*ExceptionInfo).ExceptionRecord)... | {
make_handler()
} | identifier_body |
stack_overflow.rs | // Copyright 2014 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 ... |
// We're calling into functions with stack checks,
// however stack checks by limit should be disabled on Windows
stack::record_sp_limit(0);
report_overflow();
EXCEPTION_CONTINUE_SEARCH
}
}
pub unsafe fn init() {
let mut info = mem::zeroed();
libc::GetSystemInfo(... | {
return EXCEPTION_CONTINUE_SEARCH;
} | conditional_block |
stack_overflow.rs | // Copyright 2014 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 Drop for Handler {
fn drop(&mut self) {}
}
// This is initialized in init() and only read from after
static mut PAGE_SIZE: usize = 0;
#[no_stack_check]
extern "system" fn vectored_handler(ExceptionInfo: *mut EXCEPTION_POINTERS) -> LONG {
unsafe {
let rec = &(*(*ExceptionInfo).ExceptionRecord);
... | random_line_split | |
stack_overflow.rs | // Copyright 2014 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 ... | (&mut self) {}
}
// This is initialized in init() and only read from after
static mut PAGE_SIZE: usize = 0;
#[no_stack_check]
extern "system" fn vectored_handler(ExceptionInfo: *mut EXCEPTION_POINTERS) -> LONG {
unsafe {
let rec = &(*(*ExceptionInfo).ExceptionRecord);
let code = rec.ExceptionCode;... | drop | identifier_name |
vcs.rs | use std::process::{Command,ExitStatus,Stdio};
use std::os::unix::process::ExitStatusExt;
use std::io;
use std::result;
#[derive(Debug)]
pub struct NoVcs;
impl VersionControl for NoVcs { }
#[derive(Debug)]
pub struct GitWrapper {
repo: String,
sign: bool,
}
pub fn from_path(repo_path: &str) -> Box<VersionCo... |
pub type Result<T> = result::Result<T, io::Error>;
/// Version control trait. Note that `add` and `remove` will not commit the
/// operation. Hence `commit` has to be called separatly.
pub trait VersionControl {
fn add(&self, _file: &str) -> Result<ExitStatus> {
Ok(ExitStatus::from_raw(0))
}
fn re... | println!("'{}' is not a git repo, no vcs support!", repo_path);
Box::new(NoVcs{})
}
} | random_line_split |
vcs.rs | use std::process::{Command,ExitStatus,Stdio};
use std::os::unix::process::ExitStatusExt;
use std::io;
use std::result;
#[derive(Debug)]
pub struct NoVcs;
impl VersionControl for NoVcs { }
#[derive(Debug)]
pub struct GitWrapper {
repo: String,
sign: bool,
}
pub fn from_path(repo_path: &str) -> Box<VersionCo... | (&self, args: Vec<&str>) -> Result<ExitStatus> {
let mut cmd = Command::new("git");
cmd.args(args.as_slice())
.current_dir(&self.repo);
cmd.status()
}
}
| cmd_dispatch | identifier_name |
vcs.rs | use std::process::{Command,ExitStatus,Stdio};
use std::os::unix::process::ExitStatusExt;
use std::io;
use std::result;
#[derive(Debug)]
pub struct NoVcs;
impl VersionControl for NoVcs { }
#[derive(Debug)]
pub struct GitWrapper {
repo: String,
sign: bool,
}
pub fn from_path(repo_path: &str) -> Box<VersionCo... |
}
pub type Result<T> = result::Result<T, io::Error>;
/// Version control trait. Note that `add` and `remove` will not commit the
/// operation. Hence `commit` has to be called separatly.
pub trait VersionControl {
fn add(&self, _file: &str) -> Result<ExitStatus> {
Ok(ExitStatus::from_raw(0))
}
fn... | {
println!("'{}' is not a git repo, no vcs support!", repo_path);
Box::new(NoVcs{})
} | conditional_block |
vcs.rs | use std::process::{Command,ExitStatus,Stdio};
use std::os::unix::process::ExitStatusExt;
use std::io;
use std::result;
#[derive(Debug)]
pub struct NoVcs;
impl VersionControl for NoVcs { }
#[derive(Debug)]
pub struct GitWrapper {
repo: String,
sign: bool,
}
pub fn from_path(repo_path: &str) -> Box<VersionCo... |
}
impl GitWrapper {
fn new(repo_path: &str) -> GitWrapper {
let repo_path = String::from(repo_path);
let output = Command::new("git")
.arg("config")
.arg("--bool")
.arg("--get")
.arg("pass.signcommits")
... | {
Ok(ExitStatus::from_raw(0))
} | identifier_body |
flag.rs | // Std
use std::convert::From;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter, Result};
use std::mem;
use std::rc::Rc;
use std::result::Result as StdResult;
// Internal
use args::{AnyArg, ArgSettings, Base, DispOrder, Switched};
use map::{self, VecMap};
use Arg;
#[derive(Default, Clone, Debug)]
#[... | (&mut self, s: ArgSettings) {
self.b.settings.set(s)
}
fn max_vals(&self) -> Option<u64> {
None
}
fn val_names(&self) -> Option<&VecMap<&'e str>> {
None
}
fn num_vals(&self) -> Option<u64> {
None
}
fn possible_vals(&self) -> Option<&[&'e str]> {
No... | set | identifier_name |
flag.rs | // Std
use std::convert::From;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter, Result};
use std::mem;
use std::rc::Rc;
use std::result::Result as StdResult;
// Internal
use args::{AnyArg, ArgSettings, Base, DispOrder, Switched};
use map::{self, VecMap};
use Arg;
#[derive(Default, Clone, Debug)]
#[... |
#[test]
fn flagbuilder_display_single_alias() {
let mut f = FlagBuilder::new("flg");
f.s.long = Some("flag");
f.s.aliases = Some(vec![("als", true)]);
assert_eq!(&*format!("{}", f), "--flag");
}
#[test]
fn flagbuilder_display_multiple_aliases() {
let mut f... | {
let mut f = FlagBuilder::new("flg");
f.b.settings.set(ArgSettings::Multiple);
f.s.long = Some("flag");
assert_eq!(&*format!("{}", f), "--flag");
let mut f2 = FlagBuilder::new("flg");
f2.s.short = Some('f');
assert_eq!(&*format!("{}", f2), "-f");
} | identifier_body |
flag.rs | // Std
use std::convert::From;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter, Result};
use std::mem;
use std::rc::Rc;
use std::result::Result as StdResult;
// Internal
use args::{AnyArg, ArgSettings, Base, DispOrder, Switched};
use map::{self, VecMap};
use Arg;
#[derive(Default, Clone, Debug)]
#[... | ]);
assert_eq!(&*format!("{}", f), "-f");
}
} | ("alias_not_visible", false),
("f2", true),
("f3", true),
("f4", true), | random_line_split |
flag.rs | // Std
use std::convert::From;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter, Result};
use std::mem;
use std::rc::Rc;
use std::result::Result as StdResult;
// Internal
use args::{AnyArg, ArgSettings, Base, DispOrder, Switched};
use map::{self, VecMap};
use Arg;
#[derive(Default, Clone, Debug)]
#[... |
}
}
impl<'n, 'e> DispOrder for FlagBuilder<'n, 'e> {
fn disp_ord(&self) -> usize {
self.s.disp_ord
}
}
impl<'n, 'e> PartialEq for FlagBuilder<'n, 'e> {
fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool {
self.b == other.b
}
}
#[cfg(test)]
mod test {
use super::FlagBuilder;
... | {
None
} | conditional_block |
mod.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.... | include!(concat!(env!("OUT_DIR"), "/mod.rs")); | random_line_split | |
common.rs | pub use alloc::boxed::*;
pub use core::cmp::max;
pub use core::cmp::min;
pub use core::clone::Clone;
pub use core::mem::size_of;
pub use core::mem::size_of_val;
pub use core::option::Option;
pub use core::ptr;
pub use core::sync::atomic::*;
pub use common::debug::*;
pub use common::event::*;
pub use common::queue::*;... |
#[allow(unused_variables)]
pub trait SessionItem{
fn on_irq(&mut self, irq: u8){
}
fn on_poll(&mut self){
}
fn scheme(&self) -> String{
return String::new();
}
fn open(&mut self, url: &URL) -> Box<Resource> {
return box NoneResource;
}
} | pub use graphics::window::*;
pub use syscall::call::*; | random_line_split |
common.rs | pub use alloc::boxed::*;
pub use core::cmp::max;
pub use core::cmp::min;
pub use core::clone::Clone;
pub use core::mem::size_of;
pub use core::mem::size_of_val;
pub use core::option::Option;
pub use core::ptr;
pub use core::sync::atomic::*;
pub use common::debug::*;
pub use common::event::*;
pub use common::queue::*;... |
fn scheme(&self) -> String{
return String::new();
}
fn open(&mut self, url: &URL) -> Box<Resource> {
return box NoneResource;
}
}
| {
} | identifier_body |
common.rs | pub use alloc::boxed::*;
pub use core::cmp::max;
pub use core::cmp::min;
pub use core::clone::Clone;
pub use core::mem::size_of;
pub use core::mem::size_of_val;
pub use core::option::Option;
pub use core::ptr;
pub use core::sync::atomic::*;
pub use common::debug::*;
pub use common::event::*;
pub use common::queue::*;... | (&mut self){
}
fn scheme(&self) -> String{
return String::new();
}
fn open(&mut self, url: &URL) -> Box<Resource> {
return box NoneResource;
}
}
| on_poll | identifier_name |
liveness-unused.rs | // Copyright 2014 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 ... | () {
}
| main | identifier_name |
liveness-unused.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file... | random_line_split | |
liveness-unused.rs | // Copyright 2014 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 f5b() {
for (x, _) in [1i, 2, 3].iter().enumerate() { }
//~^ ERROR unused variable: `x`
}
fn f5c() {
for (_, x) in [1i, 2, 3].iter().enumerate() {
//~^ ERROR unused variable: `x`
continue;
std::os::set_exit_status(*x); //~ WARNING unreachable statement
}
}
fn main() {
}
| {
for x in range(1i, 10) { }
//~^ ERROR unused variable: `x`
} | identifier_body |
liveness-unused.rs | // Copyright 2014 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 f5a() {
for x in range(1i, 10) { }
//~^ ERROR unused variable: `x`
}
fn f5b() {
for (x, _) in [1i, 2, 3].iter().enumerate() { }
//~^ ERROR unused variable: `x`
}
fn f5c() {
for (_, x) in [1i, 2, 3].iter().enumerate() {
//~^ ERROR unused variable: `x`
continue;
std:... | {
i
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.