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 |
|---|---|---|---|---|
sync.rs | #![crate_name = "sync"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alexander Fomin <xander.fomin@ya.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Last synced with: sync (GNU coreutils) 8.13 */
exte... | unsafe fn flush_volume(name: &str) {
let name_buffer = name.to_c_str().as_ptr();
if 0x00000003 == GetDriveTypeA(name_buffer) { // DRIVE_FIXED
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
let sliced_name_buffer = sliced_name.to_c_str().as_ptr();
... |
#[allow(unused_unsafe)] | random_line_split |
sync.rs | #![crate_name = "sync"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alexander Fomin <xander.fomin@ya.ru>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* Last synced with: sync (GNU coreutils) 8.13 */
exte... |
#[allow(unused_unsafe)]
unsafe fn find_all_volumes() -> Vec<String> {
match find_first_volume() {
(first_volume, next_volume_handle) => {
let mut volumes = vec![first_volume];
loop {
let mut name: [libc::c_char; 260] = mem::uninitialized(... | {
let mut name: [libc::c_char; 260] = mem::uninitialized(); // MAX_PATH
match FindFirstVolumeA(name.as_mut_ptr(),
name.len() as libc::uint32_t) {
-1 => { // INVALID_HANDLE_VALUE
crash!(GetLastError(), "failed to find first volume");
... | identifier_body |
issue-3447.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 ... | next: None
};
println!("{}", ls.element);
} | let ls = list {
element: S, | random_line_split |
issue-3447.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 ls = list {
element: S,
next: None
};
println!("{}", ls.element);
}
| {
let newList = list {
element: element,
next: None
};
self.next = Some(box RefCell::new(newList));
} | identifier_body |
issue-3447.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 ... | (&mut self, element: T) {
let newList = list {
element: element,
next: None
};
self.next = Some(box RefCell::new(newList));
}
}
pub fn main() {
let ls = list {
element: S,
next: None
};
println!("{}", ls.element);
}
| addEnd | identifier_name |
lib.rs | // DO NOT EDIT!
// This file was generated automatically from'src/mako/api/lib.rs.mako'
// DO NOT EDIT!
//! This documentation was generated from *replicapool* crate version *0.1.8+20150311*, where *20150311* is the exact revision of the *replicapool:v1beta2* schema built by the [mako](http://www.makotemplates.org/) c... | //! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and
//! [decodable](trait.ResponseResult.html) via ... | //! | random_line_split |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... |
None => return,
}
run_test(Some(&env::join_paths(&paths).unwrap()));
}
| {
paths.remove(i);
} | conditional_block |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... | fn run_test(path_env: Option<&OsStr>) {
const N: usize = 50;
let foo = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[dependencies]
bar = "*... | random_line_split | |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... | () {
let path = env::var_os("PATH").unwrap_or_default();
let mut paths = env::split_paths(&path).collect::<Vec<_>>();
let idx = paths
.iter()
.position(|p| p.join("git").exists() || p.join("git.exe").exists());
match idx {
Some(i) => {
paths.remove(i);
}
... | avoid_using_git | identifier_name |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... |
#[cargo_test]
fn avoid_using_git() {
let path = env::var_os("PATH").unwrap_or_default();
let mut paths = env::split_paths(&path).collect::<Vec<_>>();
let idx = paths
.iter()
.position(|p| p.join("git").exists() || p.join("git.exe").exists());
match idx {
Some(i) => {
... | {
if Command::new("git").arg("--version").output().is_err() {
return;
}
run_test(None);
} | identifier_body |
union_with_anon_struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 {
pub a: ::std::os::raw::c_uin... | unsafe {
&(*(::std::ptr::null::<foo__bindgen_ty_1>())).b as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(foo__bindgen_ty_1),
"::",
stringify!(b)
)
);
}
#[test]
fn bindgen_test_layout_foo() {
... | random_line_split | |
union_with_anon_struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 {
pub a: ::std::os::raw::c_uin... |
impl Default for foo {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
| {
assert_eq!(
::std::mem::size_of::<foo>(),
8usize,
concat!("Size of: ", stringify!(foo))
);
assert_eq!(
::std::mem::align_of::<foo>(),
4usize,
concat!("Alignment of ", stringify!(foo))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<foo>())).ba... | identifier_body |
union_with_anon_struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 {
pub a: ::std::os::raw::c_uin... | () {
assert_eq!(
::std::mem::size_of::<foo__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(foo__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<foo__bindgen_ty_1>(),
4usize,
concat!("Alignment of ", stringify!(foo__bindgen_ty_1))
);
asse... | bindgen_test_layout_foo__bindgen_ty_1 | identifier_name |
common.rs | /*
* Copyright 2014 The Android Open Source Project
*
* 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 applica... | #pragma rs java_package_name(android.hardware.camera2.cts)
#pragma rs_fp_relaxed
typedef uchar3 yuvx_444; // interleaved YUV. (y,u,v) per pixel. use.x/.y/.z to read
typedef uchar3 yuvf_420; // flexible YUV (4:2:0). use rsGetElementAtYuv to read.
#define convert_yuvx_444 convert_uchar3
#define convert_yuvf_420 __error... |
#pragma version(1) | random_line_split |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | }
actions
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[Action] [StopRecording] Server #{}",
self.server_id
)
}
}
| {
info!("{} Stopping audio recording...", self);
if let Some(channel_name) = server.channel_name(&self.voice_channel_id) {
// Notify all users in the current voice channel
for member in server.channel_voice_members(&self.voice_channel_id) {
... | conditional_block |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | {
server_id: ServerId,
voice_channel_id: ChannelId,
}
impl Action {
pub fn new(
server_id: ServerId,
voice_channel_id: ChannelId
) -> Box<Action> {
Box::new(Action {
server_id: server_id,
voice_channel_id: voice_channel_id
})
}
}
impl Actio... | Action | identifier_name |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | server_id: ServerId,
voice_channel_id: ChannelId
) -> Box<Action> {
Box::new(Action {
server_id: server_id,
voice_channel_id: voice_channel_id
})
}
}
impl ActionHandler for Action {
fn run(&mut self, bot: &mut Bot, _: &BotConfig, queue: &mut EventQue... | random_line_split | |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... |
server.stop_recording_voice(queue);
}
}
actions
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[Action] [StopRecording] Server #{}",
self.server_id
)
}... | {
let mut actions: Vec<Box<ActionHandler>> = Vec::new();
if let Some(server) = bot.get_server(&self.server_id) {
info!("{} Stopping audio recording...", self);
if let Some(channel_name) = server.channel_name(&self.voice_channel_id) {
// Notify all users in th... | identifier_body |
enums.rs | use operation::*;
/// Raw opcodes
///
/// Provides a way of storing both ARM and THUMB opcodes (which have
/// different sizes) in a single type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Opcode {
/// A raw ARM opcode
///
/// Contains a 32-bit ARM opcode in machine encoding.
Arm(u32),
/// A... |
}
| {
use arm;
use thumb;
match opcode {
Opcode::Arm(w) => {
let condition = arm::condition(w);
let operation = arm::decode(w);
Instruction::Arm(condition, operation)
}
Opcode::Thumb(s) => {
let oper... | identifier_body |
enums.rs | use operation::*;
/// Raw opcodes
///
/// Provides a way of storing both ARM and THUMB opcodes (which have
/// different sizes) in a single type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum | {
/// A raw ARM opcode
///
/// Contains a 32-bit ARM opcode in machine encoding.
Arm(u32),
/// A raw THUMB opcode
///
/// Contains a 16-bit THUMB opcode in machine encoding.
Thumb(u16),
}
macro_rules! simple_from {
($src:ty => $dst:ty as $variant:path) => {
impl From<$src> ... | Opcode | identifier_name |
enums.rs | use operation::*;
/// Raw opcodes
///
/// Provides a way of storing both ARM and THUMB opcodes (which have
/// different sizes) in a single type.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Opcode {
/// A raw ARM opcode
///
/// Contains a 32-bit ARM opcode in machine encoding.
Arm(u32),
/// A... | let condition = arm::condition(w);
let operation = arm::decode(w);
Instruction::Arm(condition, operation)
}
Opcode::Thumb(s) => {
let operation = thumb::decode(s);
Instruction::Thumb(operation)
}
... | match opcode {
Opcode::Arm(w) => { | random_line_split |
auth.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... | ,
}
}
}
#[derive(Debug)]
enum Access {
Granted,
Denied,
AuthRequired,
}
impl HttpBasicAuth {
/// Creates `HttpBasicAuth` instance with only one user.
pub fn single_user(username: &str, password: &str) -> Self {
let mut users = HashMap::new();
users.insert(username.to_owned(), password.to_owned());
HttpB... | {
Authorized::Yes
} | conditional_block |
auth.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... | (username: &str, password: &str) -> Self {
let mut users = HashMap::new();
users.insert(username.to_owned(), password.to_owned());
HttpBasicAuth {
users: users
}
}
fn is_authorized(&self, username: &str, password: &str) -> bool {
self.users.get(&username.to_owned()).map_or(false, |pass| pass == password... | single_user | identifier_name |
auth.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... | Yes,
/// Unsuccessful authorization. Handler for further work is returned.
No(Box<Handler>),
}
/// Authorization interface
pub trait Authorization : Send + Sync {
/// Checks if authorization is valid.
fn is_authorized(&self, req: &server::Request<net::HttpStream>)-> Authorized;
}
/// HTTP Basic Authorization han... | random_line_split | |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... |
// snippet-end:[kms.rust.generate-data-key]
/// Creates an AWS KMS data key.
/// # Arguments
///
/// * `[-k KEY]` - The name of the key.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variabl... | {
let resp = client
.generate_data_key()
.key_id(key)
.key_spec(DataKeySpec::Aes256)
.send()
.await?;
// Did we get an encrypted blob?
let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
let bytes = blob.as_ref();
let s = base64::encode(&... | identifier_body |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... | (client: &Client, key: &str) -> Result<(), Error> {
let resp = client
.generate_data_key()
.key_id(key)
.key_spec(DataKeySpec::Aes256)
.send()
.await?;
// Did we get an encrypted blob?
let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
let bytes =... | make_key | identifier_name |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... | println!();
if verbose {
println!("KMS client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Key: {}", &key);
println!();
}
let shared_config = ... |
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2")); | random_line_split |
generate-data-key.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_kms::model::DataKeySpec;
use aws_sdk_kms::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
stru... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
make_key(&client, &key).await
}
| {
println!("KMS client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Key: {}", &key);
println!();
} | conditional_block |
rk4.rs | use libc::c_double;
/// Given a differential function dx(x, t),
/// initial condition x0,
/// and a list of times t,
/// find x(t) at each point in t
pub fn odeint(dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: &Vec<c_double>) -> Vec<c_double> {
// Need there to be at least t... | let mut times = Vec::<f64>::new();
let mut i = 0.0;
while i <= 10.0 {
times.push(i);
i += 0.1;
}
let x0 = 0.0;
let mut result = odeint(&free_fall, x0, ×);
let expected_value = -490.5;
//println!("printing a result vector: {:?... |
#[test]
fn test_free_fall() { | random_line_split |
rk4.rs | use libc::c_double;
/// Given a differential function dx(x, t),
/// initial condition x0,
/// and a list of times t,
/// find x(t) at each point in t
pub fn odeint(dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: &Vec<c_double>) -> Vec<c_double> {
// Need there to be at least t... |
#[test]
fn rk4_compiles() {
}
#[test]
fn test_velocity_one() {
let ref t = vec![0.0, 1.0];
let x0 = 0.0;
let mut result = odeint(&velocity_one, x0, t);
assert!((result.pop().unwrap() - 1.0).abs() < THRESHOLD);
}
#[test]
fn test_length() {
le... | {
let g = -9.81;
g*t
} | identifier_body |
rk4.rs | use libc::c_double;
/// Given a differential function dx(x, t),
/// initial condition x0,
/// and a list of times t,
/// find x(t) at each point in t
pub fn odeint(dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: &Vec<c_double>) -> Vec<c_double> {
// Need there to be at least t... | (dx: (&Fn(c_double, c_double) -> c_double),
x0: c_double, t_vec: *mut Vec<c_double>) -> *mut Vec<c_double> {
unsafe { unsafe_alloc_vec_f64!(odeint(dx, x0, &*t_vec)) }
}
#[cfg(test)]
mod tests_rk4 {
use super::*;
const THRESHOLD: f64 = 0.0000001;
// Test differential to give to odei... | odeint_64 | identifier_name |
photos.rs | use api::{Collection, Id, OwnerId, Timestamp};
request_ref! {
struct Search for ["photos.search"](v => 5.37) -> Collection<Photo> {
sized {
lat: f32 = () => {},
long: f32 = () => {},
start_time: Timestamp = () => {},
end_time: Timestamp = () => {},
... | (&self) -> &str {
use self::Sort::*;
match *self {
DateAdded => "0",
Popularity => "1",
}
}
}
| as_ref | identifier_name |
photos.rs | use api::{Collection, Id, OwnerId, Timestamp};
request_ref! {
struct Search for ["photos.search"](v => 5.37) -> Collection<Photo> {
sized {
lat: f32 = () => {},
long: f32 = () => {},
start_time: Timestamp = () => {},
end_time: Timestamp = () => {},
... | }
}
} | Popularity => "1", | random_line_split |
opaque-template-inst-member.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct | {
pub _address: u8,
}
/// This should not end up deriving Debug/Hash because its `mBlah` field cannot derive
/// Debug/Hash because the instantiation's definition cannot derive Debug/Hash.
#[repr(C)]
pub struct ContainsOpaqueTemplate {
pub mBlah: [u32; 101usize],
pub mBaz: ::std::os::raw::c_int,
}
#[test]
... | OpaqueTemplate | identifier_name |
opaque-template-inst-member.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct OpaqueTemplate {
pub _address: u8,
}
/// This should not end up deriving Debug/Hash because its `mBlah` field cannot derive
/// Debu... |
}
impl ::std::cmp::PartialEq for ContainsOpaqueTemplate {
fn eq(&self, other: &ContainsOpaqueTemplate) -> bool {
&self.mBlah[..] == &other.mBlah[..] && self.mBaz == other.mBaz
}
}
/// This should not end up deriving Debug/Hash either, for similar reasons, although
/// we're exercising base member edges... | {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
} | identifier_body |
opaque-template-inst-member.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct OpaqueTemplate {
pub _address: u8,
}
/// This should not end up deriving Debug/Hash because its `mBlah` field cannot derive
/// Debu... | &self.mBlah[..] == &other.mBlah[..] && self.mBaz == other.mBaz
}
}
/// This should not end up deriving Debug/Hash either, for similar reasons, although
/// we're exercising base member edges now.
#[repr(C)]
pub struct InheritsOpaqueTemplate {
pub _base: [u8; 401usize],
pub wow: *mut ::std::os::raw::... | impl ::std::cmp::PartialEq for ContainsOpaqueTemplate {
fn eq(&self, other: &ContainsOpaqueTemplate) -> bool { | random_line_split |
float.rs | #[macro_use]
extern crate nom;
use nom::{IResult,digit};
| use std::str::FromStr;
named!(unsigned_float <f32>, map_res!(
map_res!(
recognize!(
alt!(
delimited!(digit, tag!("."), opt!(complete!(digit))) |
delimited!(opt!(digit), tag!("."), digit)
)
),
str::from_utf8
),
FromStr::from_str
));
named!(float <f32>, map!(
pair!(
o... | use std::str; | random_line_split |
float.rs | #[macro_use]
extern crate nom;
use nom::{IResult,digit};
use std::str;
use std::str::FromStr;
named!(unsigned_float <f32>, map_res!(
map_res!(
recognize!(
alt!(
delimited!(digit, tag!("."), opt!(complete!(digit))) |
delimited!(opt!(digit), tag!("."), digit)
)
),
str::from_ut... | () {
assert_eq!(unsigned_float(&b"123.456"[..]), IResult::Done(&b""[..], 123.456));
assert_eq!(unsigned_float(&b"0.123"[..]), IResult::Done(&b""[..], 0.123));
assert_eq!(unsigned_float(&b"123.0"[..]), IResult::Done(&b""[..], 123.0));
assert_eq!(unsigned_float(&b"123."[..]), IResult::Done(&b""[..], 123.0)... | unsigned_float_test | identifier_name |
float.rs | #[macro_use]
extern crate nom;
use nom::{IResult,digit};
use std::str;
use std::str::FromStr;
named!(unsigned_float <f32>, map_res!(
map_res!(
recognize!(
alt!(
delimited!(digit, tag!("."), opt!(complete!(digit))) |
delimited!(opt!(digit), tag!("."), digit)
)
),
str::from_ut... | {
assert_eq!(float(&b"123.456"[..]), IResult::Done(&b""[..], 123.456));
assert_eq!(float(&b"+123.456"[..]), IResult::Done(&b""[..], 123.456));
assert_eq!(float(&b"-123.456"[..]), IResult::Done(&b""[..], -123.456));
} | identifier_body | |
gio_futures_await.rs | extern crate gio;
extern crate glib;
use gio::prelude::*;
use futures::prelude::*;
use std::str;
// Throughout our chained futures, we convert all errors to strings
// via map_err() return them directly.
async fn read_file(file: gio::File) -> Result<(), String> {
// Try to open the file.
let strm = file
... | l.run();
c.pop_thread_default();
} | random_line_split | |
gio_futures_await.rs | extern crate gio;
extern crate glib;
use gio::prelude::*;
use futures::prelude::*;
use std::str;
// Throughout our chained futures, we convert all errors to strings
// via map_err() return them directly.
async fn read_file(file: gio::File) -> Result<(), String> {
// Try to open the file.
let strm = file
... | () {
let c = glib::MainContext::default();
let l = glib::MainLoop::new(Some(&c), false);
c.push_thread_default();
let file = gio::File::new_for_path("Cargo.toml");
let l_clone = l.clone();
let future = async move {
match read_file(file).await {
Ok(()) => (),
Er... | main | identifier_name |
gio_futures_await.rs | extern crate gio;
extern crate glib;
use gio::prelude::*;
use futures::prelude::*;
use std::str;
// Throughout our chained futures, we convert all errors to strings
// via map_err() return them directly.
async fn read_file(file: gio::File) -> Result<(), String> {
// Try to open the file.
let strm = file
... |
c.pop_thread_default();
}
| {
let c = glib::MainContext::default();
let l = glib::MainLoop::new(Some(&c), false);
c.push_thread_default();
let file = gio::File::new_for_path("Cargo.toml");
let l_clone = l.clone();
let future = async move {
match read_file(file).await {
Ok(()) => (),
Err(e... | identifier_body |
pre_parse.rs | use futures::{Stream, StreamExt, TryFutureExt};
use juniper::{
executor::{execute_validated_query_async, get_operation, resolve_validated_subscription},
graphql_object, graphql_subscription,
parser::parse_document_source,
validation::{validate_input_values, visit_all_rules, ValidatorContext},
EmptyM... | () -> UserStream {
Box::pin(futures::stream::iter(vec![Ok(User)]))
}
}
#[derive(Clone)]
pub struct User;
#[graphql_object(context = Context)]
impl User {
fn id() -> i32 {
1
}
}
type Schema = RootNode<'static, Query, EmptyMutation<Context>, Subscription>;
#[tokio::test]
async fn query_doc... | users | identifier_name |
pre_parse.rs | use futures::{Stream, StreamExt, TryFutureExt};
use juniper::{
executor::{execute_validated_query_async, get_operation, resolve_validated_subscription},
graphql_object, graphql_subscription,
parser::parse_document_source,
validation::{validate_input_values, visit_all_rules, ValidatorContext},
EmptyM... | &document,
&operation,
&root_node,
&Variables::new(),
&Context {},
)
.map_ok(|(stream, errors)| juniper_subscriptions::Connection::from_stream(stream, errors))
.await
.unwrap();
let _ = stream.next().await.unwrap();
} |
let operation = get_operation(&document, None).unwrap();
assert!(operation.item.operation_type == OperationType::Subscription);
let mut stream = resolve_validated_subscription( | random_line_split |
thin.rs | use anyhow::Result;
use std::path::PathBuf;
use thinp::file_utils;
use thinp::io_engine::*;
use crate::args;
use crate::common::fixture::*;
use crate::common::process::*;
use crate::common::target::*;
use crate::common::test_dir::TestDir;
use crate::common::thin_xml_generator::{write_xml, SingleThinS};
//-----------... | (md: &PathBuf) -> Result<()> {
let args = args!["-o", &md, "--set-needs-check"];
run_ok(thin_generate_metadata_cmd(args))?;
Ok(())
}
pub fn generate_metadata_leaks(
md: &PathBuf,
nr_blocks: u64,
expected: u32,
actual: u32,
) -> Result<()> {
let nr_blocks_str = nr_blocks.to_string();
... | set_needs_check | identifier_name |
thin.rs | use anyhow::Result;
use std::path::PathBuf;
use thinp::file_utils;
use thinp::io_engine::*;
use crate::args;
use crate::common::fixture::*;
use crate::common::process::*;
use crate::common::target::*;
use crate::common::test_dir::TestDir;
use crate::common::thin_xml_generator::{write_xml, SingleThinS};
//-----------... | // Take a few snapshots.
let mut snap_id = 2;
for _i in 0..10 {
// take a snapshot
let snap_id_str = snap_id.to_string();
let args = args!["-o", &md, "--create-snap", &snap_id_str, "--origin", "1"];
run_ok(thin_generate_metadata_cmd(args))?;
// partially overwrite th... | {
let md = mk_zeroed_md(td)?;
let args = args!["-o", &md, "--format", "--nr-data-blocks", "102400"];
run_ok(thin_generate_metadata_cmd(args))?;
// Create a 2GB device
let args = args!["-o", &md, "--create-thin", "1"];
run_ok(thin_generate_metadata_cmd(args))?;
let args = args![
"-o"... | identifier_body |
blake2b.rs | KEYBYTES],
key_length: u8,
last_node: u8,
digest_length: u8,
computed: bool, // whether the final digest has been computed
param: Blake2bParam
}
impl Clone for Blake2b { fn clone(&self) -> Blake2b { *self } }
#[derive(Copy, Clone)]
struct Blake2bParam {
digest_length: u8,
key_length: u8,
... |
fn increment_counter(&mut self, inc : u64) {
self.t[0] += inc;
self.t[1] += if self.t[0] < inc { 1 } else { 0 };
}
fn init0(param: Blake2bParam, digest_length: u8, key: &[u8]) -> Blake2b {
assert!(key.len() <= BLAKE2B_KEYBYTES);
let mut b = Blake2b {
h: IV,
... | {
if self.last_node!=0 {
self.set_lastnode();
}
self.f[0] = 0xFFFFFFFFFFFFFFFF;
} | identifier_body |
blake2b.rs | KEYBYTES],
key_length: u8,
last_node: u8,
digest_length: u8,
computed: bool, // whether the final digest has been computed
param: Blake2bParam
}
impl Clone for Blake2b { fn clone(&self) -> Blake2b { *self } }
#[derive(Copy, Clone)]
struct Blake2bParam {
digest_length: u8,
key_length: u8,
... | (outlen: usize) -> Blake2b {
assert!(outlen > 0 && outlen <= BLAKE2B_OUTBYTES);
Blake2b::init_param(Blake2b::default_param(outlen as u8), &[])
}
fn apply_key(&mut self) {
let mut block : [u8; BLAKE2B_BLOCKBYTES] = [0; BLAKE2B_BLOCKBYTES];
copy_memory(&self.key[..self.key_length ... | new | identifier_name |
blake2b.rs | use std::io::Write;
use cryptoutil::WriteExt;
let mut param_bytes : [u8; 64] = [0; 64];
{
let mut writer: &mut [u8] = &mut param_bytes;
writer.write_u8(self.param.digest_length).unwrap();
writer.write_u8(self.param.key_length).unwrap();
write... | mod mac_tests {
use blake2b::Blake2b; | random_line_split | |
blake2b.rs | KEYBYTES],
key_length: u8,
last_node: u8,
digest_length: u8,
computed: bool, // whether the final digest has been computed
param: Blake2bParam
}
impl Clone for Blake2b { fn clone(&self) -> Blake2b { *self } }
#[derive(Copy, Clone)]
struct Blake2bParam {
digest_length: u8,
key_length: u8,
... |
self.f[0] = 0xFFFFFFFFFFFFFFFF;
}
fn increment_counter(&mut self, inc : u64) {
self.t[0] += inc;
self.t[1] += if self.t[0] < inc { 1 } else { 0 };
}
fn init0(param: Blake2bParam, digest_length: u8, key: &[u8]) -> Blake2b {
assert!(key.len() <= BLAKE2B_KEYBYTES);
... | {
self.set_lastnode();
} | conditional_block |
gameboy.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | 3 => On,
_ => Off,
}
}
}
impl Into<u8> for Color {
fn into(self) -> u8 {
match self {
Color::Off => 0,
Color::Light => 1,
Color::Dark => 2,
Color::On => 3,
}
}
}
pub const CPU_SPEED_HZ: usize = 4_194_304;
pub const HIRAM_SIZE: usize = 0x80;
pub const HIRAM_EMPTY: ... | pub fn from_u8(value: u8) -> Color {
use self::Color::*;
match value {
1 => Light,
2 => Dark, | random_line_split |
gameboy.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... |
}
pub const CPU_SPEED_HZ: usize = 4_194_304;
pub const HIRAM_SIZE: usize = 0x80;
pub const HIRAM_EMPTY: HiramData = [0; HIRAM_SIZE];
pub const ROM_BANK_SIZE: usize = 0x4000;
pub const RAM_BANK_SIZE: usize = 0x2000;
pub const SCREEN_WIDTH: usize = 160;
pub const SCREEN_HEIGHT: usize = 144;
pub const SCREEN_PIXELS: usi... | {
match self {
Color::Off => 0,
Color::Light => 1,
Color::Dark => 2,
Color::On => 3,
}
} | identifier_body |
gameboy.rs | // This file is part of Mooneye GB.
// Copyright (C) 2014-2020 Joonas Javanainen <joonas.javanainen@gmail.com>
//
// Mooneye GB 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... | {
Off = 0,
Light = 1,
Dark = 2,
On = 3,
}
impl Color {
#[inline]
pub fn from_u8(value: u8) -> Color {
use self::Color::*;
match value {
1 => Light,
2 => Dark,
3 => On,
_ => Off,
}
}
}
impl Into<u8> for Color {
fn into(self) -> u8 {
match self {
Color::Off... | Color | identifier_name |
thunk.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 ... | }
pub fn invoke(self, arg: A) -> R {
self.invoke.invoke(arg)
}
}
pub trait Invoke<A=(),R=()> {
fn invoke(self: Box<Self>, arg: A) -> R;
}
impl<A,R,F> Invoke<A,R> for F
where F : FnOnce(A) -> R
{
fn invoke(self: Box<F>, arg: A) -> R {
let f = *self;
f(arg)
}
} | random_line_split | |
thunk.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, arg: A) -> R {
self.invoke.invoke(arg)
}
}
pub trait Invoke<A=(),R=()> {
fn invoke(self: Box<Self>, arg: A) -> R;
}
impl<A,R,F> Invoke<A,R> for F
where F : FnOnce(A) -> R
{
fn invoke(self: Box<F>, arg: A) -> R {
let f = *self;
f(arg)
}
}
| invoke | identifier_name |
thunk.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<A,R> Thunk<A,R> {
pub fn with_arg<F>(func: F) -> Thunk<A,R>
where F : FnOnce(A) -> R, F : Send
{
Thunk {
invoke: box func
}
}
pub fn invoke(self, arg: A) -> R {
self.invoke.invoke(arg)
}
}
pub trait Invoke<A=(),R=()> {
fn invoke(self: Box<Se... | {
Thunk::with_arg(move|()| func())
} | identifier_body |
regionmanip.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 ... |
/// Pushes a constraint that `r_a <= r_b`, due to `opt_ty`
fn push_sub_region_constraint(&mut self,
opt_ty: Option<Ty<'tcx>>,
r_a: ty::Region,
r_b: ty::Region) {
self.out.push(RegionSubRegionConstrain... | {
// Indicates that we have found borrowed content with a lifetime
// of at least `r_b`. This adds a constraint that `r_b` must
// outlive the region `r_a` on top of the stack.
//
// As an example, imagine walking a type like:
//
// &'a &'b T
// ... | identifier_body |
regionmanip.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 ... | (&mut self,
ty: Ty<'tcx>,
def_id: ast::DefId,
generics: &ty::Generics<'tcx>,
substs: &Substs<'tcx>)
{
// The generic declarations from the type, appropriately
// substituted for the actual sub... | accumulate_from_adt | identifier_name |
regionmanip.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 ... |
ty::Contravariant | ty::Invariant => {
// If the parameter is contravariant or
// invariant, there may indeed be reachable
// data with this lifetime. See other case for
// more details.
... | {
// Ignore covariant or bivariant region
// parameters. To understand why, consider a
// struct `Foo<'a>`. If `Foo` contains any
// references with lifetime `'a`, then `'a` must
// be at least contr... | conditional_block |
regionmanip.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 ... | // `region_bound` that user specified must imply the
// region bounds required from all of the trait types:
for &r_d in required_region_bounds.iter() {
// Each of these is an instance of the `'c <= 'b`
// constraint above
self.out.push(RegionSubRegionConstrain... | // `bounds.region_bound`:
let r_c = region_bound;
self.push_region_constraint_from_top(r_c);
// And then, in turn, to be well-formed, the | random_line_split |
back.rs | //! Back-end module for the task queue. The back-end is running
//! on a separate thread. All it does is listening to a command
//! channel and starting new tasks when the time comes.
use std::sync::atomic::*;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::HashMap;... | (bran::Handle);
impl ReadyTask {
pub fn run(self) {
use bran::fiber::State;
let ReadyTask(task) = self;
match task.run() {
State::Pending(signal) => {
worker::requeue(task, signal);
}
State::PendingTimeout(_, _) => {
panic!... | ReadyTask | identifier_name |
back.rs | //! Back-end module for the task queue. The back-end is running
//! on a separate thread. All it does is listening to a command
//! channel and starting new tasks when the time comes.
use std::sync::atomic::*;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::HashMap;... |
/// Create a new deque
pub fn new_deque(&self) -> (usize,
deque::Worker<ReadyTask>,
Receiver<worker::Command>) {
let buffer = deque::BufferPool::new();
let (worker, stealer) = buffer.deque();
let (send, recv) = channel();... | {
// read the current active count, OR in the BLOCK
// flag if needed for the wait
match wait {
Wait::None | Wait::Active => {
self.active.store(true, Ordering::SeqCst);
}
Wait::Pending => ()
};
let mut guard = self.workers.loc... | identifier_body |
back.rs | //! Back-end module for the task queue. The back-end is running
//! on a separate thread. All it does is listening to a command
//! channel and starting new tasks when the time comes.
use std::sync::atomic::*;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{Sender, Receiver, channel};
use std::collections::HashMap;... | /// been completed.
pub fn enqueue(back: Arc<Backend>, task: bran::Handle, after: Signal) {
after.callback(move || {
if!back.active.load(Ordering::SeqCst) {
let try_thread = worker::start(ReadyTask(task));
match try_thread {
Ok(b) => b,
... | }
});
}
/// Start a task that will run once all the Handle's have | random_line_split |
lib.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_id="p2dux#0.1"]
#![crate_type="rlib"]
#![desc = "All UX/Frontend-specific cod... | else {
self.fps_ctr += 1;
}
}
pub fn get_curr_fps(&self) -> uint { self.curr_fps }
pub fn get_ms_since(&self) -> uint { (self.now_time - self.last_time) as uint }
}
| {
self.curr_fps = self.fps_ctr;
self.fps_ctr = 0;
self.next_fps_time = self.now_time + 1000u64;
} | conditional_block |
lib.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_id="p2dux#0.1"]
#![crate_type="rlib"]
#![desc = "All UX/Frontend-specific cod... |
}
| { (self.now_time - self.last_time) as uint } | identifier_body |
lib.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_id="p2dux#0.1"]
#![crate_type="rlib"]
#![desc = "All UX/Frontend-specific cod... | {
pub last_time: u64,
pub now_time: u64,
pub next_fps_time: u64,
pub fps_ctr: uint,
pub curr_fps: uint
}
impl TimeTracker {
pub fn new() -> TimeTracker {
let curr_time = precise_time_ns() / 1000000u64;
let mut tt = TimeTracker {
last_time: curr_time,
now_... | TimeTracker | identifier_name |
lib.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_id="p2dux#0.1"]
#![crate_type="rlib"]
#![desc = "All UX/Frontend-specific cod... | pub next_fps_time: u64,
pub fps_ctr: uint,
pub curr_fps: uint
}
impl TimeTracker {
pub fn new() -> TimeTracker {
let curr_time = precise_time_ns() / 1000000u64;
let mut tt = TimeTracker {
last_time: curr_time,
now_time: curr_time,
next_fps_time: curr_t... | pub last_time: u64,
pub now_time: u64, | random_line_split |
import.rs | // Copyright 2015, 2016 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 la... | /// Blocks enacted by this import.
///
/// They should be ordered from oldest to newest.
pub enacted: Vec<H256>,
/// Number of blocks retracted by this import.
pub retracted: usize,
} | random_line_split | |
import.rs | // Copyright 2015, 2016 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 la... | {
/// Traces to import.
pub traces: FlatBlockTraces,
/// Hash of traces block.
pub block_hash: H256,
/// Number of traces block.
pub block_number: BlockNumber,
/// Blocks enacted by this import.
///
/// They should be ordered from oldest to newest.
pub enacted: Vec<H256>,
/// Number of blocks retracted by t... | ImportRequest | identifier_name |
once.rs | use consumer::*;
use stream::*;
/// A stream that emits an element exactly once.
///
/// This `struct` is created by the [`once()`] function. See its documentation
/// for more.
///
/// [`once()`]: fn.once.html
#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Once<T> {
value: T,
}... | <T>(value: T) -> Once<T> {
Once { value: value }
}
impl<T> Stream for Once<T> {
type Item = T;
fn consume<C>(self, mut consumer: C)
where C: Consumer<Self::Item>
{
consumer.emit(self.value);
}
}
| once | identifier_name |
once.rs | use consumer::*;
use stream::*;
/// A stream that emits an element exactly once.
///
/// This `struct` is created by the [`once()`] function. See its documentation
/// for more.
///
/// [`once()`]: fn.once.html
#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Once<T> {
value: T,
}... |
impl<T> Stream for Once<T> {
type Item = T;
fn consume<C>(self, mut consumer: C)
where C: Consumer<Self::Item>
{
consumer.emit(self.value);
}
}
| {
Once { value: value }
} | identifier_body |
once.rs | use consumer::*; | ///
/// This `struct` is created by the [`once()`] function. See its documentation
/// for more.
///
/// [`once()`]: fn.once.html
#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Once<T> {
value: T,
}
/// Creates a stream that emits an element exactly once.
///
/// # Examples
///
... | use stream::*;
/// A stream that emits an element exactly once. | random_line_split |
selection_range.rs | use serde::{Deserialize, Serialize};
use crate::{
PartialResultParams, Position, Range, StaticTextDocumentRegistrationOptions,
TextDocumentIdentifier, WorkDoneProgressOptions, WorkDoneProgressParams,
};
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
p... | }
impl From<SelectionRangeRegistrationOptions> for SelectionRangeProviderCapability {
fn from(from: SelectionRangeRegistrationOptions) -> Self {
Self::RegistrationOptions(from)
}
}
impl From<SelectionRangeOptions> for SelectionRangeProviderCapability {
fn from(from: SelectionRangeOptions) -> Self ... | pub enum SelectionRangeProviderCapability {
Simple(bool),
Options(SelectionRangeOptions),
RegistrationOptions(SelectionRangeRegistrationOptions), | random_line_split |
selection_range.rs | use serde::{Deserialize, Serialize};
use crate::{
PartialResultParams, Position, Range, StaticTextDocumentRegistrationOptions,
TextDocumentIdentifier, WorkDoneProgressOptions, WorkDoneProgressParams,
};
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
p... | {
/// The text document.
pub text_document: TextDocumentIdentifier,
/// The positions inside the text document.
pub positions: Vec<Position>,
#[serde(flatten)]
pub work_done_progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
... | SelectionRangeParams | identifier_name |
base.rs | // Copyright 2012-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-MI... |
cx.consume_stats().into_inner()
};
(stats, ModuleCodegen {
name: cgu_name.to_string(),
module_llvm: llvm_module,
kind: ModuleKind::Regular,
})
}
}
pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
let sect = match attrs.l... | {
cx.debuginfo_finalize();
} | conditional_block |
base.rs | // Copyright 2012-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-MI... | cgu_name: InternedString)
-> (Stats, ModuleCodegen<ModuleLlvm>)
{
let backend = LlvmCodegenBackend(());
let cgu = tcx.codegen_unit(cgu_name);
// Instantiate monomorphizations without filling out definitions yet...
let llvm_module = backend.new_metadata(tcx.sess, &cgu_... | {
let start_time = Instant::now();
let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
tcx,
cgu_name,
... | identifier_body |
base.rs | // Copyright 2012-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-MI... | (&mut self) -> Option<&'ll Value> {
let old = self.cur;
if let Some(old) = old {
self.cur = unsafe { (self.step)(old) };
}
old
}
}
pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
unsafe {
ValueIter {
cur: llvm::LLVMGetFirstGlobal... | next | identifier_name |
base.rs | // Copyright 2012-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-MI... | // If this codegen unit contains the main function, also create the
// wrapper here
maybe_create_entry_wrapper::<Builder>(&cx);
// Run replace-all-uses-with for statics that need it
for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
... | }
| random_line_split |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | ,
hir::ItemKind::Trait(ref _is_auto, ref _unsafe, ref _generics, _bounds, trait_items) => {
// note: we need to check if the trait is exported so we can't use
// `LateLintPass::check_trait_item` here.
for tit in trait_items {
let tit_ = cx.... | {
let desc = "a function";
let attrs = cx.tcx.hir().attrs(it.hir_id());
check_missing_inline_attrs(cx, attrs, it.span, desc);
} | conditional_block |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | (&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
use rustc_middle::ty::{ImplContainer, TraitContainer};
if rustc_middle::lint::in_external_macro(cx.sess(), impl_item.span) || is_executable_or_proc_macro(cx) {
return;
}
// If the item being implemente... | check_impl_item | identifier_name |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | hir::ItemKind::Trait(ref _is_auto, ref _unsafe, ref _generics, _bounds, trait_items) => {
// note: we need to check if the trait is exported so we can't use
// `LateLintPass::check_trait_item` here.
for tit in trait_items {
let tit_ = cx.tc... | let desc = "a function";
let attrs = cx.tcx.hir().attrs(it.hir_id());
check_missing_inline_attrs(cx, attrs, it.span, desc);
}, | random_line_split |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => {},
hir::TraitItemKind::Fn(..) => {
if tit.defaultness.has_value() {
// trait method with default body needs inline in case
... | {
if rustc_middle::lint::in_external_macro(cx.sess(), it.span) || is_executable_or_proc_macro(cx) {
return;
}
if !cx.access_levels.is_exported(it.def_id) {
return;
}
match it.kind {
hir::ItemKind::Fn(..) => {
let desc = "a func... | identifier_body |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (&mut self, c: Coordinates) -> Result<()> {
self.get_header_mut()
.insert("gps.coordinates", c.into())
.map(|_| ())
.chain_err(|| GPSEK::HeaderWriteError)
}
fn get_coordinates(&self) -> Result<Option<Coordinates>> {
match self.get_header().read("gps.coordinates"... | set_coordinates | identifier_name |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... |
fn get_store() -> Store {
use libimagstore::file_abstraction::InMemoryFileAbstraction;
let backend = Box::new(InMemoryFileAbstraction::new());
Store::new_with_backend(PathBuf::from("/"), &None, backend).unwrap()
}
#[test]
fn test_set_gps() {
setup_logging();
l... | {
use env_logger;
let _ = env_logger::init().unwrap_or(());
} | identifier_body |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | let store = get_store();
let mut entry = store.create(PathBuf::from("test_setget_gps")).unwrap();
let coordinates = Coordinates {
latitude: GPSValue::new(0, 0, 0),
longitude: GPSValue::new(0, 0, 0),
};
let res = entry.set_coordinates(coordinates);
... | random_line_split | |
tvec.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
use back::abi;
use llvm;
use llvm::ValueRef;
use trans::base::*;
use trans::base;
use trans::build::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::common::*;
use tr... | (bcx: Block,
llval: ValueRef,
vec_length: usize)
-> (ValueRef, ValueRef) {
let ccx = bcx.ccx();
let base = expr::get_dataptr(bcx, llval);
let len = C_uint(ccx, vec_length);
(base, len)
}
/// Converts a vector int... | get_fixed_base_and_len | identifier_name |
tvec.rs | // option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
use back::abi;
use llvm;
use llvm::ValueRef;
use trans::base::*;
use trans::base;
use trans::build::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::common::*;
use ... | slice_expr: &ast::Expr,
content_expr: &ast::Expr)
-> DatumBlock<'blk, 'tcx, Expr> {
let fcx = bcx.fcx;
let ccx = fcx.ccx;
let mut bcx = bcx;
debug!("trans_slice_vec(slice_expr={})",
bcx.e... |
/// &[...] allocates memory on the stack and writes the values into it, returning the vector (the
/// caller must make the reference). "..." is similar except that the memory can be statically
/// allocated and we return a reference (strings are always by-ref).
pub fn trans_slice_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx... | random_line_split |
tvec.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
use back::abi;
use llvm;
use llvm::ValueRef;
use trans::base::*;
use trans::base;
use trans::build::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::common::*;
use tr... | }
};
}
/// &[...] allocates memory on the stack and writes the values into it, returning the vector (the
/// caller must make the reference). "..." is similar except that the memory can be statically
/// allocated and we return a reference (strings are always by-ref).
pub fn trans_slice_vec<'blk, 'tcx>(b... | {
//!
//
// [...] allocates a fixed-size array and moves it around "by value".
// In this case, it means that the caller has already given us a location
// to store the array of the suitable size, so all we have to do is
// generate the content.
debug!("trans_fixed_vstore(expr={}, dest={})"... | identifier_body |
loc.rs | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Loc<T, P> {
pub inner: T,
pub pos: P,
}
impl<T, P> ::std::ops::Deref for Loc<T, P> {
type Target = T;
fn deref(&self) -> &T {
&self.inner
}
}
impl<T, P> ::std::fmt::Display for Loc<T, P>
where
T: ::std::fmt::Display,
{
... | (&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.inner)
}
}
impl<T, P> ::std::fmt::Debug for Loc<T, P>
where
T: ::std::fmt::Debug,
P: ::std::fmt::Debug,
{
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "<{:?}@{:?}>", sel... | fmt | identifier_name |
loc.rs | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Loc<T, P> {
pub inner: T,
pub pos: P,
}
impl<T, P> ::std::ops::Deref for Loc<T, P> {
type Target = T;
fn deref(&self) -> &T {
&self.inner
}
}
impl<T, P> ::std::fmt::Display for Loc<T, P>
where
T: ::std::fmt::Display,
{
... | write!(f, "<{:?}@{:?}>", self.inner, self.pos)
}
} | random_line_split | |
loc.rs | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Loc<T, P> {
pub inner: T,
pub pos: P,
}
impl<T, P> ::std::ops::Deref for Loc<T, P> {
type Target = T;
fn deref(&self) -> &T {
&self.inner
}
}
impl<T, P> ::std::fmt::Display for Loc<T, P>
where
T: ::std::fmt::Display,
{
... |
}
impl<T, P> ::std::fmt::Debug for Loc<T, P>
where
T: ::std::fmt::Debug,
P: ::std::fmt::Debug,
{
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "<{:?}@{:?}>", self.inner, self.pos)
}
}
| {
write!(f, "{}", self.inner)
} | identifier_body |
test_optimizers.rs | extern crate autograd as ag;
extern crate ndarray;
use ag::prelude::*;
use ag::tensor_ops as T;
use ag::variable::NamespaceTrait;
use ag::{optimizers, VariableEnvironment};
use ndarray::array;
#[test]
fn test_adam() {
let mut env = make_env();
let opt = optimizers::Adam::default(
"my_unique_adam",
... | let mean_loss = T::reduce_mean(loss, &[0], false);
let ns = g.default_namespace();
let (vars, grads) = optimizers::grad_helper(&[mean_loss], &ns);
opt.update(&vars, &grads, g, ag::Feeder::new());
});
} | let z = T::matmul(x, w) + b;
let loss = T::sparse_softmax_cross_entropy(z, &y); | random_line_split |
test_optimizers.rs | extern crate autograd as ag;
extern crate ndarray;
use ag::prelude::*;
use ag::tensor_ops as T;
use ag::variable::NamespaceTrait;
use ag::{optimizers, VariableEnvironment};
use ndarray::array;
#[test]
fn test_adam() {
let mut env = make_env();
let opt = optimizers::Adam::default(
"my_unique_adam",
... | {
env.run(|g| {
let x = T::convert_to_tensor(array![[0.1, 0.2], [0.2, 0.1]], g).show();
let y = T::convert_to_tensor(array![1., 0.], g).show();
let w = g.variable("w");
let b = g.variable("b");
let z = T::matmul(x, w) + b;
let loss = T::sparse_softmax_cross_entropy(z,... | identifier_body | |
test_optimizers.rs | extern crate autograd as ag;
extern crate ndarray;
use ag::prelude::*;
use ag::tensor_ops as T;
use ag::variable::NamespaceTrait;
use ag::{optimizers, VariableEnvironment};
use ndarray::array;
#[test]
fn test_adam() {
let mut env = make_env();
let opt = optimizers::Adam::default(
"my_unique_adam",
... | () -> VariableEnvironment<'static, f64> {
let mut env = ag::VariableEnvironment::new();
let rng = ag::ndarray_ext::ArrayRng::<f64>::default();
env.name("w").set(rng.glorot_uniform(&[2, 2]));
env.name("b").set(ag::ndarray_ext::zeros(&[1, 2]));
env
}
fn run<O: Optimizer<f64>>(opt: O, env: VariableEnv... | make_env | identifier_name |
term.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 ... | () -> Term {
Term {
err: Box::new(io::stderr())
}
}
pub fn err(&mut self, msg: &str) {
// swallow any errors
let _ = writeln!(&mut self.err, "{}", msg);
env::set_exit_status(101);
}
}
| new | identifier_name |
term.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 ... |
pub fn err(&mut self, msg: &str) {
// swallow any errors
let _ = writeln!(&mut self.err, "{}", msg);
env::set_exit_status(101);
}
}
| {
Term {
err: Box::new(io::stderr())
}
} | identifier_body |
term.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 ... |
pub fn err(&mut self, msg: &str) {
// swallow any errors
let _ = writeln!(&mut self.err, "{}", msg);
env::set_exit_status(101);
}
} | err: Box::new(io::stderr())
}
} | random_line_split |
mod.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | use std::time::Duration;
use bincode;
use futures::{sync::mpsc, Future, Stream};
use log;
use serde::Serialize;
use tokio::net::TcpListener;
use service::ButtonService;
use shutdown::{Shutdown, ShutdownCause};
#[cfg(unix)]
fn notify_server_startup<T>(path: &Path, message: &T) -> Result<(), io::Error>
where
T: Se... | random_line_split | |
mod.rs | // Copyright (c) 2019 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, d... | (self, idle: Duration) {
let (tx, rx) = mpsc::channel(0);
let service = ButtonService::new(tx);
let timeout = Shutdown::new(idle, rx).map(|message| match message {
ShutdownCause::Idle(duration) => {
log::info!(
"Shutting down due to being idle fo... | run | identifier_name |
kmesg_buffer.rs | extern crate errno;
extern crate libc;
#[cfg(target_os = "macos")]
use std::str;
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")] | #[cfg(target_os = "linux")]
use std::sync::mpsc;
#[cfg(target_os = "linux")]
use std::sync::mpsc::Receiver;
#[cfg(target_os = "linux")]
use std::{thread, time};
// See https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/msgbuf.h
#[cfg(target_os = "macos")]
const MAX_MSG_BSIZE: usize = 1024 * 1024;
// this e... | use std::io::{BufRead, BufReader}; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.