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 |
|---|---|---|---|---|
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead o... | /// Information on what to do on task failure.
pub failure: Failure,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can notify others when it's done.
pub layout_shutdown_chan: Sender<()>,
... | ///
/// TODO(pcwalton): When we convert this to use IPC, this will need to become an
/// `IpcAnySender`.
pub paint_chan: Box<Any + Send>, | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead o... | {
/// Id of the parent of this new pipeline.
pub containing_pipeline_id: PipelineId,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the new frame associated with this pipeline.
pub subpage_id: SubpageId,
/// Network request data which will be initiated by t... | NewLayoutInfo | identifier_name |
ethcore_set.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.... | () -> Arc<TestMinerService> {
Arc::new(TestMinerService::default())
}
fn client_service() -> Arc<TestBlockChainClient> {
Arc::new(TestBlockChainClient::default())
}
fn network_service() -> Arc<TestManageNetwork> {
Arc::new(TestManageNetwork)
}
fn ethcore_set_client(client: &Arc<TestBlockChainClient>, miner: &Arc<... | miner_service | identifier_name |
ethcore_set.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 ethcore_set_client(client: &Arc<TestBlockChainClient>, miner: &Arc<TestMinerService>, net: &Arc<TestManageNetwork>) -> EthcoreSetClient<TestBlockChainClient, TestMinerService> {
EthcoreSetClient::new(client, miner, &(net.clone() as Arc<ManageNetwork>))
}
#[test]
fn rpc_ethcore_set_min_gas_price() {
let miner = ... | {
Arc::new(TestManageNetwork)
} | identifier_body |
ethcore_set.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 rpc_ethcore_set_min_gas_price() {
let miner = miner_service();
let client = client_service();
let network = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_set_client(&client, &miner, &network).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_setMinGasPrice", "param... | EthcoreSetClient::new(client, miner, &(net.clone() as Arc<ManageNetwork>))
}
#[test] | 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 ... | fn as_raw_handle(&self) -> Handle {
self.as_inner().handle()
}
}
impl AsRawHandle for io::net::pipe::UnixAcceptor {
fn as_raw_handle(&self) -> Handle {
self.as_inner().handle()
}
}
/// Extract raw sockets.
pub trait AsRawSocket {
fn as_raw_socket(&self) -> Socket;
}
impl AsRawSock... | 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()
}
}
impl AsRawHandle for io::net::pipe::UnixStream {
fn as_raw_handle(&self) -> Handle {
self.as_inner().handle()
}
}
impl AsRawHandle for io::net::pipe::UnixListener {
fn as_raw_handle(&self) -> Handle {
self.as_inner().handle()
... | as_raw_handle | 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 AsRawHandle for io::net::pipe::UnixStream {
fn as_raw_handle(&self) -> Handle {
self.as_inner().handle()
}
}
impl AsRawHandle for io::net::pipe::UnixListener {
fn as_raw_handle(&self) -> Handle {
self.as_inner().handle()
}
}
impl AsRawHandle for io::net::pipe::UnixAcceptor {
... | {
self.as_inner().handle()
} | identifier_body |
parse.rs | use nom::{
character::complete::multispace0,
error::ParseError,
sequence::delimited,
IResult,
Slice,
};
pub mod expression;
pub mod path;
pub mod tokens;
pub mod tree;
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct FileInfo<'a> {
pub filename: &'a str,
pub full_source: &'a s... | let mut spaces = 0;
for c in line[..(self.get_column() - 1)].chars() {
column += 1;
match c {
'\t' => {
tabs += 1;
}
_ => spaces += 1,
}
}
(line, column, "\t".repeat(tabs) + &(" ".re... |
let mut column = 0;
let mut tabs = 0; | random_line_split |
parse.rs | use nom::{
character::complete::multispace0,
error::ParseError,
sequence::delimited,
IResult,
Slice,
};
pub mod expression;
pub mod path;
pub mod tokens;
pub mod tree;
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct FileInfo<'a> {
pub filename: &'a str,
pub full_source: &'a s... | (s: &str) -> Span {
Span::new_extra(
s,
FileInfo {
filename: "<test>",
full_source: s,
},
)
}
}
| sp | identifier_name |
parse.rs | use nom::{
character::complete::multispace0,
error::ParseError,
sequence::delimited,
IResult,
Slice,
};
pub mod expression;
pub mod path;
pub mod tokens;
pub mod tree;
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct FileInfo<'a> {
pub filename: &'a str,
pub full_source: &'a s... |
fn get_line_column_padding(&self) -> (&str, usize, String) {
let line = self.get_line();
let mut column = 0;
let mut tabs = 0;
let mut spaces = 0;
for c in line[..(self.get_column() - 1)].chars() {
column += 1;
match c {
'\t' => {
... | {
let full_source = self.extra.full_source;
let offset = self.location_offset();
let start = full_source.slice(..offset).rfind('\n').map_or(0, |x| x + 1);
full_source.slice(offset..).find('\n').map_or_else(
|| full_source.slice(start..),
|end| full_source.slice(s... | identifier_body |
environment.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use lox_object::LoxObject;
use scanner::Token;
use interpreter::{RuntimeError, RuntimeResult};
pub struct Environment {
enclosing: Option<Rc<Environment>>,
values: RefCell<HashMap<String, LoxObject>>,
}
impl Environment {
pub fn new(... |
pub fn define(&self, name: &str, value: &LoxObject) {
self.values.borrow_mut().insert(name.to_owned(), value.clone());
}
pub fn assign(&self, name: &Token, value: &LoxObject) -> RuntimeResult<()> {
let mut values = self.values.borrow_mut();
if values.contains_key(&name.lexeme) {
... | {
Self {
enclosing: Some(enclosing),
values: RefCell::new(HashMap::new()),
}
} | identifier_body |
environment.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use lox_object::LoxObject;
use scanner::Token;
use interpreter::{RuntimeError, RuntimeResult};
pub struct Environment {
enclosing: Option<Rc<Environment>>,
values: RefCell<HashMap<String, LoxObject>>,
}
impl Environment {
pub fn new(... |
}
}
pub fn get(&self, name: &Token) -> RuntimeResult<LoxObject> {
match self.values.borrow().get(&name.lexeme) {
Some(object) => Ok(object.clone()),
None => {
if let Some(ref env) = self.enclosing {
env.get(name)
} els... | {
Err(RuntimeError::new(
name,
&format!("Undefined variable '{}'.", name.lexeme),
))
} | conditional_block |
environment.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use lox_object::LoxObject;
use scanner::Token;
use interpreter::{RuntimeError, RuntimeResult};
pub struct Environment {
enclosing: Option<Rc<Environment>>,
values: RefCell<HashMap<String, LoxObject>>,
}
impl Environment {
pub fn new(... | (&self, name: &Token, value: &LoxObject) -> RuntimeResult<()> {
let mut values = self.values.borrow_mut();
if values.contains_key(&name.lexeme) {
values.insert(name.lexeme.to_owned(), value.clone());
Ok(())
} else {
if let Some(ref enclosing_env) = self.enclo... | assign | identifier_name |
environment.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use lox_object::LoxObject;
use scanner::Token;
use interpreter::{RuntimeError, RuntimeResult};
pub struct Environment {
enclosing: Option<Rc<Environment>>,
values: RefCell<HashMap<String, LoxObject>>,
}
impl Environment {
pub fn new(... |
pub fn define(&self, name: &str, value: &LoxObject) {
self.values.borrow_mut().insert(name.to_owned(), value.clone());
}
pub fn assign(&self, name: &Token, value: &LoxObject) -> RuntimeResult<()> {
let mut values = self.values.borrow_mut();
if values.contains_key(&name.lexeme) {
... | } | random_line_split |
type_use.rs | .org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
... |
pub fn type_needs_inner(cx: &Context,
use_: uint,
ty: ty::t,
enums_seen: @List<DefId>) {
do ty::maybe_walk_ty(ty) |ty| {
if ty::type_has_params(ty) {
match ty::get(ty).sty {
/*
This previou... | {
// Optimization -- don't descend type if all params already have this use
if cx.uses.iter().any(|&elt| elt & use_ != use_) {
type_needs_inner(cx, use_, ty, @Nil);
}
} | identifier_body |
type_use.rs | .org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
... | <'a>(&mut self, e:@Expr, cx: &'a Context) {
visit::walk_expr(self, e, cx);
mark_for_expr(cx, e);
}
fn visit_local<'a>(&mut self, l:@Local, cx: &'a Context) {
visit::walk_local(self, l, cx);
node_type_needs(cx, use_repr, l.id);
}
fn visit_pat<'a>(&mut sel... | visit_expr | identifier_name |
type_use.rs | lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those term... | // used. This is imprecise, but simple. Getting it right is
// tricky because the substs on the call and the substs on the
// default method differ, because of substs on the trait/impl.
let is_default = ty::provided_source(ccx.tcx, fn_id_loc).is_some();
// We also mark all of the params as used if ... | random_line_split | |
errors3.rs | // errors3.rs
// This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError;
fn main() {
let m... |
}
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}
| {
tokens -= cost;
println!("You now have {} tokens.", tokens);
} | conditional_block |
errors3.rs | // errors3.rs
// This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError;
fn | () {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
}
pub fn total_cost(item_quantity: &... | main | identifier_name |
errors3.rs | // errors3.rs
// This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError;
fn main() {
let m... |
Ok(qty * cost_per_item + processing_fee)
} | let qty = item_quantity.parse::<i32>()?; | random_line_split |
errors3.rs | // errors3.rs
// This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
// I AM NOT DONE
use std::num::ParseIntError;
fn main() |
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}
| {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}
} | identifier_body |
lib.rs | //! The `pact_verifier` crate provides a number of exported functions using C bindings for
//! controlling the pact verification process. These can be used in any language that supports C bindings.
#![warn(missing_docs)]
use std::ffi::CStr;
use std::ffi::CString;
use std::str;
use std::panic::catch_unwind;
use std::e... | Ok(val) => val,
Err(cause) => {
log::error!("Caught a general panic: {:?}", cause);
3
}
}
}
| {
if args.is_null() {
return 2;
}
let result = catch_unwind(|| {
let runtime = tokio::runtime::Runtime::new().unwrap();
runtime.block_on(async {
let args_raw = CStr::from_ptr(args).to_string_lossy().into_owned();
let args: Vec<String> = args_raw.lines().map(|s| s.to_string()).collect();
... | identifier_body |
lib.rs | //! The `pact_verifier` crate provides a number of exported functions using C bindings for
//! controlling the pact verification process. These can be used in any language that supports C bindings.
#![warn(missing_docs)]
use std::ffi::CStr;
use std::ffi::CString;
use std::str;
use std::panic::catch_unwind;
use std::e... | (args: *const c_char) -> i32 {
if args.is_null() {
return 2;
}
let result = catch_unwind(|| {
let runtime = tokio::runtime::Runtime::new().unwrap();
runtime.block_on(async {
let args_raw = CStr::from_ptr(args).to_string_lossy().into_owned();
let args: Vec<String> = args_raw.lines().map(|s... | verify | identifier_name |
lib.rs | //! The `pact_verifier` crate provides a number of exported functions using C bindings for
//! controlling the pact verification process. These can be used in any language that supports C bindings.
#![warn(missing_docs)]
use std::ffi::CStr;
use std::ffi::CString;
use std::str;
use std::panic::catch_unwind;
use std::e... | pub mod verifier;
/// Package version
pub static VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
/// Get the current library version
///
/// # Errors
///
/// An empty string indicates an error determining the current crate version
#[no_mangle]
pub extern "C" fn version() -> *const c_char {
VERSION.as_pt... | random_line_split | |
method_self_arg2.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 ... | Bar::bar3(box self);
}
}
pub trait Bar {
fn foo1(&self);
fn foo2(self);
fn foo3(self: Box<Self>);
fn bar1(&self) {
unsafe { COUNT *= 7; }
}
fn bar2(self) {
unsafe { COUNT *= 11; }
}
fn bar3(self: Box<Self>) {
unsafe { COUNT *= 13; }
}
}
impl Bar... | Bar::foo2(self);
Bar::foo3(box self);
Bar::bar1(&self);
Bar::bar2(self); | random_line_split |
method_self_arg2.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 bar3(self: Box<Self>) {
unsafe { COUNT *= 13; }
}
}
impl Bar for Foo {
fn foo1(&self) {
unsafe { COUNT *= 2; }
}
fn foo2(self) {
unsafe { COUNT *= 3; }
}
fn foo3(self: Box<Foo>) {
unsafe { COUNT *= 5; }
}
}
| {
unsafe { COUNT *= 11; }
} | identifier_body |
method_self_arg2.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) {
unsafe { COUNT *= 11; }
}
fn bar3(self: Box<Self>) {
unsafe { COUNT *= 13; }
}
}
impl Bar for Foo {
fn foo1(&self) {
unsafe { COUNT *= 2; }
}
fn foo2(self) {
unsafe { COUNT *= 3; }
}
fn foo3(self: Box<Foo>) {
unsafe { COUNT *= 5; }
... | bar2 | identifier_name |
plugin.rs | _PRESET_NAME_LEN`
/// [return]: true for success
GetPresetName,
/// Deprecated.
_CopyPreset,
/// Deprecated.
_ConnectIn,
/// Deprecated.
_ConnectOut,
/// [index]: input index
/// [ptr]: `VstPinProperties`
/// [return]: 1 if supported
GetInputInfo,
/// [index]: outpu... | (host: HostCallback) -> Self where Self: Sized + Default {
Default::default()
}
/// Called when plugin is fully initialized.
fn init(&mut self) { trace!("Initialized vst plugin."); }
/// Set the current preset to the index specified by `preset`.
fn change_preset(&mut self, preset: i32) { ... | new | identifier_name |
plugin.rs | /// [return]: true for success
GetPresetName,
/// Deprecated.
_CopyPreset,
/// Deprecated.
_ConnectIn,
/// Deprecated.
_ConnectOut,
/// [index]: input index
/// [ptr]: `VstPinProperties`
/// [return]: 1 if supported
GetInputInfo,
/// [index]: output index
/// [p... | {
let mut buf = vec![0; max];
self.callback(self.effect, opcode, index, value, buf.as_mut_ptr() as *mut c_void, opt);
String::from_utf8_lossy(&buf).chars().take_while(|c| *c != '\0').collect()
} | identifier_body | |
plugin.rs | ::MAX_PRESET_NAME_LEN`
/// [return]: true for success
GetPresetName,
/// Deprecated.
_CopyPreset,
/// Deprecated.
_ConnectIn,
/// Deprecated.
_ConnectOut,
/// [index]: input index
/// [ptr]: `VstPinProperties`
/// [return]: 1 if supported
GetInputInfo,
/// [index]: ... | fn get_output_info(&self, output: i32) -> ChannelInfo {
ChannelInfo::new(format!("Output channel {}", output),
Some(format!("Out {}", output)),
true, None)
}
}
/// A reference to the host which allows the plugin to call back and access information.
///
... | true, None)
}
/// Get information about an output channel. Only used by some hosts. | random_line_split |
non_windows_non_macos.rs | use std::os::unix::fs::{PermissionsExt, FileTypeExt};
use libc::{O_RDONLY, c_ulong, close, ioctl, open};
use std::os::unix::ffi::OsStrExt;
use std::fs::{FileType, Metadata};
use std::ffi::CString;
use std::path::Path;
include!(concat!(env!("OUT_DIR"), "/ioctl-data/ioctl.rs"));
// Stolen from https://unix.supergloba... | (meta: &Metadata) -> bool {
(meta.permissions().mode() & (S_IXUSR | S_IXGRP | S_IXOTH))!= 0
}
| file_executable | identifier_name |
non_windows_non_macos.rs | use std::os::unix::fs::{PermissionsExt, FileTypeExt};
use libc::{O_RDONLY, c_ulong, close, ioctl, open};
use std::os::unix::ffi::OsStrExt;
use std::fs::{FileType, Metadata};
use std::ffi::CString;
use std::path::Path;
include!(concat!(env!("OUT_DIR"), "/ioctl-data/ioctl.rs"));
// Stolen from https://unix.supergloba... |
}
meta.len()
}
/// Check if file is marked executable
pub fn file_executable(meta: &Metadata) -> bool {
(meta.permissions().mode() & (S_IXUSR | S_IXGRP | S_IXOTH))!= 0
}
| {
let ok = unsafe { ioctl(dev_file, BLKGETSIZE, &mut block_count as *mut c_ulong) } == 0;
unsafe { close(dev_file) };
if ok {
return block_count as u64 * 512;
}
} | conditional_block |
non_windows_non_macos.rs | use std::os::unix::fs::{PermissionsExt, FileTypeExt};
use libc::{O_RDONLY, c_ulong, close, ioctl, open};
use std::os::unix::ffi::OsStrExt;
use std::fs::{FileType, Metadata};
use std::ffi::CString;
use std::path::Path;
include!(concat!(env!("OUT_DIR"), "/ioctl-data/ioctl.rs"));
// Stolen from https://unix.supergloba... |
/// Check file length responsibly
#[inline(always)]
pub fn file_length<P: AsRef<Path>>(meta: &Metadata, path: &P) -> u64 {
file_length_impl(meta, path.as_ref())
}
fn file_length_impl(meta: &Metadata, path: &Path) -> u64 {
if is_device(&meta.file_type()) {
let mut block_count: c_ulong = 0;
le... | {
tp.is_block_device() || tp.is_char_device() || tp.is_fifo() || tp.is_socket()
} | identifier_body |
non_windows_non_macos.rs | use std::os::unix::fs::{PermissionsExt, FileTypeExt};
use libc::{O_RDONLY, c_ulong, close, ioctl, open};
use std::os::unix::ffi::OsStrExt;
use std::fs::{FileType, Metadata};
use std::ffi::CString;
use std::path::Path;
include!(concat!(env!("OUT_DIR"), "/ioctl-data/ioctl.rs"));
// Stolen from https://unix.supergloba... | /// OS-specific check for fileness
pub fn is_device(tp: &FileType) -> bool {
tp.is_block_device() || tp.is_char_device() || tp.is_fifo() || tp.is_socket()
}
/// Check file length responsibly
#[inline(always)]
pub fn file_length<P: AsRef<Path>>(meta: &Metadata, path: &P) -> u64 {
file_length_impl(meta, path.as_... | random_line_split | |
issue-43106-gating-of-bench.rs | // Copyright 2017 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 main() { } | random_line_split | |
issue-43106-gating-of-bench.rs | // Copyright 2017 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 ... | { } | identifier_body | |
issue-43106-gating-of-bench.rs | // Copyright 2017 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 |
issue-4252.rs | // Copyright 2013-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-MI... | }
}
impl<T: X + std::fmt::Debug> Drop for Z<T> {
fn drop(&mut self) {
// These statements used to cause an ICE.
self.x.call(self);
self.x.default_method(self);
}
}
pub fn main() {
let _z = Z {x: Y(42)};
} | random_line_split | |
issue-4252.rs | // Copyright 2013-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-MI... | (isize);
#[derive(Debug)]
struct Z<T: X+std::fmt::Debug> {
x: T
}
impl X for Y {
fn call<T: std::fmt::Debug>(&self, x: &T) {
println!("X::call {:?} {:?}", self, x);
}
}
impl<T: X + std::fmt::Debug> Drop for Z<T> {
fn drop(&mut self) {
// These statements used to cause an ICE.
... | Y | identifier_name |
issue-4252.rs | // Copyright 2013-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-MI... |
}
#[derive(Debug)]
struct Y(isize);
#[derive(Debug)]
struct Z<T: X+std::fmt::Debug> {
x: T
}
impl X for Y {
fn call<T: std::fmt::Debug>(&self, x: &T) {
println!("X::call {:?} {:?}", self, x);
}
}
impl<T: X + std::fmt::Debug> Drop for Z<T> {
fn drop(&mut self) {
// These statements u... | {
println!("X::default_method {:?}", x);
} | identifier_body |
directory.rs | #![allow(unused_parens)]
use truetype::{Result, Tape, Value, Walue};
use crate::layout::feature::Variations;
use crate::layout::{Features, Lookups, Scripts};
/// A layout directory.
#[derive(Clone, Debug)]
#[rustfmt::skip]
pub struct | <T> {
pub major_version: (u16), // MajorVersion
pub minor_version: (u16), // MinorVersion
pub scripts_offset: (u16), // ScriptList
pub features_offset: (u16), // FeatureList
pub lookups_offset: (u16), // LookupList
pub variations_offset: (u32), // FeatureVariations
pub scrip... | Directory | identifier_name |
directory.rs | #![allow(unused_parens)]
use truetype::{Result, Tape, Value, Walue};
use crate::layout::feature::Variations;
use crate::layout::{Features, Lookups, Scripts};
/// A layout directory.
#[derive(Clone, Debug)]
#[rustfmt::skip]
pub struct Directory<T> {
pub major_version: (u16), // MajorVersion
pub minor_vers... | scripts: scripts,
features: features,
lookups: lookups,
variations: variations,
})
}
} | random_line_split | |
directory.rs | #![allow(unused_parens)]
use truetype::{Result, Tape, Value, Walue};
use crate::layout::feature::Variations;
use crate::layout::{Features, Lookups, Scripts};
/// A layout directory.
#[derive(Clone, Debug)]
#[rustfmt::skip]
pub struct Directory<T> {
pub major_version: (u16), // MajorVersion
pub minor_vers... |
_ => raise!("found an unknown version of the directory table"),
}
let scripts_offset = tape.take()?;
let features_offset = tape.take()?;
let lookups_offset = tape.take()?;
let variations_offset = match (major_version, minor_version) {
(1, 1) => tape.take(... | {} | conditional_block |
unrooted_must_root.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 rustc::hir::{self, ExprKind};
use rustc::hir::intravisit as visit;
use rustc::hir::map as ast_map;
use rustc::... |
}
match expr.node {
// Trait casts from #[must_root] types are not allowed
ExprKind::Cast(ref subexpr, _) => require_rooted(cx, self.in_new_function, &*subexpr),
// This catches assignments... the main point of this would be to catch mutable
// reference... | {
cx.span_lint(UNROOTED_MUST_ROOT,
subexpr.span,
&format!("Expression of type {:?} must be rooted", ty))
} | conditional_block |
unrooted_must_root.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 rustc::hir::{self, ExprKind};
use rustc::hir::intravisit as visit;
use rustc::hir::map as ast_map;
use rustc::... |
/// All enums containing #[must_root] types must be #[must_root] themselves
fn check_variant(&mut self, cx: &LateContext, var: &hir::Variant, _gen: &hir::Generics) {
let ref map = cx.tcx.hir;
if map.expect_item(map.get_parent(var.node.data.id())).attrs.iter().all(|a|!a.check_name("must_root"))... | {
let item = match cx.tcx.hir.get(id) {
ast_map::Node::NodeItem(item) => item,
_ => cx.tcx.hir.expect_item(cx.tcx.hir.get_parent(id)),
};
if item.attrs.iter().all(|a| !a.check_name("must_root")) {
for ref field in def.fields() {
let def_id = cx... | identifier_body |
unrooted_must_root.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 rustc::hir::{self, ExprKind};
use rustc::hir::intravisit as visit;
use rustc::hir::map as ast_map;
use rustc::... | visit::FnKind::Closure(_) => return,
};
if!in_derive_expn(span) {
let def_id = cx.tcx.hir.local_def_id(id);
let sig = cx.tcx.type_of(def_id).fn_sig(cx.tcx);
for (arg, ty) in decl.inputs.iter().zip(sig.inputs().skip_binder().iter()) {
if i... | let in_new_function = match kind {
visit::FnKind::ItemFn(n, _, _, _, _) |
visit::FnKind::Method(Ident { name: n, .. }, _, _, _) => {
&*n.as_str() == "new" || n.as_str().starts_with("new_")
} | random_line_split |
unrooted_must_root.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 rustc::hir::{self, ExprKind};
use rustc::hir::intravisit as visit;
use rustc::hir::map as ast_map;
use rustc::... | (&self) -> LintArray {
lint_array!(UNROOTED_MUST_ROOT)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnrootedPass {
/// All structs containing #[must_root] types must be #[must_root] themselves
fn check_struct_def(&mut self,
cx: &LateContext,
def: &hi... | get_lints | identifier_name |
mod.rs | // Copyright 2014-2016 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! This module contains various useful pattern matching algorithms.
//! The implementations are based on the lectu... | //! * BOM algorithm: fast for long patterns and small alphabet.
//! * KMP algorithm: the classical ancestor.
//! * Ukkonens algorithm: approximate pattern matching with dynamic programming.
//! * Myers algorithm: linear-time approximate pattern matching with edit distance for small patterns
//!
//! Another fast pattern... | //!
//! * Algorithm of Horspool: fastest for a sufficiently large alphabet
//! * Shift And algorithm: fast for patterns with less than 64 symbols and very small alphabets.
//! * BNDM algorithm: fast for patterns with less than 64 symbols. | random_line_split |
log_syntax-trace_macros-macro-locations.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 ... | log_syntax!());
} | random_line_split | |
log_syntax-trace_macros-macro-locations.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 ... | {
// statements
trace_macros!(false);
log_syntax!();
// expressions
(trace_macros!(false),
log_syntax!());
} | identifier_body | |
log_syntax-trace_macros-macro-locations.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 ... | () {
// statements
trace_macros!(false);
log_syntax!();
// expressions
(trace_macros!(false),
log_syntax!());
}
| main | identifier_name |
iter-all.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!(![1u, 2u].all(is_even));
assert!([2u, 4u].all(is_even));
assert!([].all(is_even));
assert!(!old_iter::all(&Some(1u), is_even));
assert!(old_iter::all(&Some(2u), is_even));
assert!(old_iter::all(&None::<uint>, is_even));
}
| main | identifier_name |
iter-all.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!(!old_iter::all(&Some(1u), is_even));
assert!(old_iter::all(&Some(2u), is_even));
assert!(old_iter::all(&None::<uint>, is_even));
} |
pub fn main() {
assert!(![1u, 2u].all(is_even));
assert!([2u, 4u].all(is_even));
assert!([].all(is_even)); | random_line_split |
iter-all.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!(![1u, 2u].all(is_even));
assert!([2u, 4u].all(is_even));
assert!([].all(is_even));
assert!(!old_iter::all(&Some(1u), is_even));
assert!(old_iter::all(&Some(2u), is_even));
assert!(old_iter::all(&None::<uint>, is_even));
} | identifier_body | |
test_future_or.rs | use eventual::*;
use std::sync::mpsc::channel;
#[test]
pub fn test_or_first_success_async() {
let (c1, f1) = Future::<&'static str, ()>::pair();
let (c2, f2) = Future::<&'static str, ()>::pair();
let (tx1, rx) = channel();
let tx2 = tx1.clone();
c1.receive(move |c| {
tx1.send("first").unwr... | () {
let (c, f) = Future::<&'static str, i32>::pair();
let (tx, rx) = channel();
f.or_else(move |e| {
assert_eq!(123, e);
Ok::<&'static str, ()>("caught")
}).receive(move |res| {
tx.send(res.unwrap()).unwrap();
});
c.fail(123);
assert_eq!(rx.recv().unwrap(), "caugh... | test_or_else_complete_before_receive | identifier_name |
test_future_or.rs | use eventual::*;
use std::sync::mpsc::channel;
#[test]
pub fn test_or_first_success_async() {
let (c1, f1) = Future::<&'static str, ()>::pair();
let (c2, f2) = Future::<&'static str, ()>::pair();
let (tx1, rx) = channel();
let tx2 = tx1.clone();
c1.receive(move |c| {
tx1.send("first").unwr... | {
let (c, f) = Future::<&'static str, i32>::pair();
let (tx, rx) = channel();
f.or_else(move |e| {
assert_eq!(123, e);
Ok::<&'static str, ()>("caught")
}).receive(move |res| {
tx.send(res.unwrap()).unwrap();
});
c.fail(123);
assert_eq!(rx.recv().unwrap(), "caught")... | identifier_body | |
test_future_or.rs | use eventual::*; | let (c1, f1) = Future::<&'static str, ()>::pair();
let (c2, f2) = Future::<&'static str, ()>::pair();
let (tx1, rx) = channel();
let tx2 = tx1.clone();
c1.receive(move |c| {
tx1.send("first").unwrap();
c.unwrap().complete("zomg");
});
c2.receive(move |res| {
if let ... | use std::sync::mpsc::channel;
#[test]
pub fn test_or_first_success_async() { | random_line_split |
test_future_or.rs | use eventual::*;
use std::sync::mpsc::channel;
#[test]
pub fn test_or_first_success_async() {
let (c1, f1) = Future::<&'static str, ()>::pair();
let (c2, f2) = Future::<&'static str, ()>::pair();
let (tx1, rx) = channel();
let tx2 = tx1.clone();
c1.receive(move |c| {
tx1.send("first").unwr... |
});
let or = f1.or(f2);
// No interest registered yet
assert!(rx.try_recv().is_err());
let res = or.await().unwrap();
assert_eq!(res, "zomg");
assert_eq!("first", rx.recv().unwrap());
assert_eq!("winning", rx.recv().unwrap());
}
#[test]
pub fn test_or_else_complete_before_receive()... | {
tx2.send("winning").unwrap();
} | conditional_block |
unboxed-closure-sugar-default.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 main() { }
| {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(int,),()>, Foo(int) >();
// In angle version, we supply something other than the default
eq::< Foo<(int,),(),int>, Foo(int) >();
//~^ ERROR not implemented
// S... | identifier_body |
unboxed-closure-sugar-default.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 ... | <'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(int,),()>, Foo(int) >();
// In angle version, we supply something other than the default
eq::< Foo<(int,),(),int>, Foo(int) >();
//~^ ERROR not implemented... | test | identifier_name |
unboxed-closure-sugar-default.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 test<'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(int,),()>, Foo(int) >();
// In angle version, we supply something other than the default
eq::< Foo<(int,),(),int>, Foo(int) >();
//~^ ERROR not imp... | fn eq<A: ?Sized,B: ?Sized>() where A : Eq<B> { } | random_line_split |
craw.rs | //! Module for parsing Canon CR3 files that are ISO Base Media Format
//! aka video/mp4 streams.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use super::{
... |
BoxType::CanonTableOffset => {
let count = be_u32(&mut b)?;
for _i in 0..count {
skip(&mut b, 4)?; // index. We do not care.
let offset = be_u64(&mut b)?;
let size = be_u64(&mut b)?;
if offset ==... | {
let size = b.head.size - b.head.offset;
let data = read_buf(&mut b, size)?;
header.cncv = data.to_vec();
skip_box_remain(&mut b)?;
} | conditional_block |
craw.rs | //! Module for parsing Canon CR3 files that are ISO Base Media Format
//! aka video/mp4 streams.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use super::{
... | <T: Read>(f: &mut BMFFBox<T>) -> super::Result<CrawHeader> {
let mut header = CrawHeader::default();
let mut iter = f.box_iter();
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::CanonCompressorVersion => {
let size = b.head.size - b.head.offset;
... | parse_craw_header | identifier_name |
craw.rs | //! Module for parsing Canon CR3 files that are ISO Base Media Format
//! aka video/mp4 streams.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use super::{
... | data_reference_index: u16,
) -> super::Result<super::SampleEntry> {
skip(src, 54)?;
let mut is_jpeg = false;
{
let mut iter = src.box_iter();
while let Some(mut b) = iter.next_box()? {
debug!("Box size {}", b.head.size);
match b.head.name {
BoxType... | height: u16, | random_line_split |
boss.rs | use super::{Attack, Fighter};
use std::fmt;
use std::fmt::{Display, Formatter};
pub struct Boss {
max_health: usize,
health: usize,
attack_power: usize,
defense: usize,
}
pub const DEFAULT_BOSS: Boss = Boss {
max_health: 58,
health: 58,
attack_power: 9,
defense: 2,
};
impl Display for... | (&self) -> usize {
self.defense
}
fn prepare_for_fight(&mut self) {
self.health = self.max_health
}
}
impl Default for Boss {
fn default() -> Self {
DEFAULT_BOSS
}
}
| get_defense | identifier_name |
boss.rs | use super::{Attack, Fighter};
use std::fmt;
use std::fmt::{Display, Formatter};
pub struct Boss {
max_health: usize,
health: usize,
attack_power: usize,
defense: usize,
}
pub const DEFAULT_BOSS: Boss = Boss {
max_health: 58,
health: 58,
attack_power: 9,
defense: 2,
};
impl Display for... |
fn get_defense(&self) -> usize {
self.defense
}
fn prepare_for_fight(&mut self) {
self.health = self.max_health
}
}
impl Default for Boss {
fn default() -> Self {
DEFAULT_BOSS
}
}
| {
Some(Attack::new(self.attack_power, 0))
} | identifier_body |
boss.rs | use super::{Attack, Fighter};
use std::fmt;
use std::fmt::{Display, Formatter};
pub struct Boss {
max_health: usize,
health: usize,
attack_power: usize,
defense: usize,
}
pub const DEFAULT_BOSS: Boss = Boss {
max_health: 58,
health: 58,
attack_power: 9,
defense: 2,
};
impl Display for... | self.health = attack.calculate_new_health::<Boss>(self);
}
fn get_attack(&self) -> Option<Attack> {
Some(Attack::new(self.attack_power, 0))
}
fn get_defense(&self) -> usize {
self.defense
}
fn prepare_for_fight(&mut self) {
self.health = self.max_health
}
}... |
fn take_hit(&mut self, attack: Attack) { | random_line_split |
boss.rs | use super::{Attack, Fighter};
use std::fmt;
use std::fmt::{Display, Formatter};
pub struct Boss {
max_health: usize,
health: usize,
attack_power: usize,
defense: usize,
}
pub const DEFAULT_BOSS: Boss = Boss {
max_health: 58,
health: 58,
attack_power: 9,
defense: 2,
};
impl Display for... |
}
fn take_hit(&mut self, attack: Attack) {
self.health = attack.calculate_new_health::<Boss>(self);
}
fn get_attack(&self) -> Option<Attack> {
Some(Attack::new(self.attack_power, 0))
}
fn get_defense(&self) -> usize {
self.defense
}
fn prepare_for_fight(&mut ... | {
println!("Boss: {} HP", self.health);
} | conditional_block |
main.rs | use std::fmt::Display;
#[derive(Debug)]
struct ImportantExcerpt<'a> {
part: &'a str // if hold ref, need lifetime anno
}
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
// one of the param is self, so all return
// lifetime is same to self
fn announce_and_return_part(&s... | // mannually, to let borrow checker help us
// fn longest(str1: &str, str2: &str) -> &str {
// since scope is always nested, will be the shortest of str1 and str2
// need to make the lifetime of result relative to at least
// one of the args
fn longest<'a>(str1: &'a str, str2: &'a str) -> &'a str {
if str1.len() > ... |
// compiler don't know if the result is ref to str1 or str2,
// so the borrow checker don't know enough info to check
// anything here. We programmers need to express our intentions | random_line_split |
main.rs | use std::fmt::Display;
#[derive(Debug)]
struct ImportantExcerpt<'a> {
part: &'a str // if hold ref, need lifetime anno
}
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 |
// one of the param is self, so all return
// lifetime is same to self
fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
self.part
}
}
fn main() {
// --- lifetime prevent dangling ref
/*
let r;
{ // x no... | {
3
} | identifier_body |
main.rs | use std::fmt::Display;
#[derive(Debug)]
struct ImportantExcerpt<'a> {
part: &'a str // if hold ref, need lifetime anno
}
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
// one of the param is self, so all return
// lifetime is same to self
fn announce_and_return_part(&s... | () {
// --- lifetime prevent dangling ref
/*
let r;
{ // x not live long enough
let x = 5;
r = &x;
}
println!("r: {}", r);
*/
// ---
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("T... | main | identifier_name |
main.rs | use std::fmt::Display;
#[derive(Debug)]
struct ImportantExcerpt<'a> {
part: &'a str // if hold ref, need lifetime anno
}
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
// one of the param is self, so all return
// lifetime is same to self
fn announce_and_return_part(&s... | else {
str2
}
}
fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str
where T: Display
{
println!("Announcement! {}", ann);
if x.len() > y.len() {
x
} else {
y
}
} | {
str1
} | conditional_block |
macro-at-most-once-rep-2015-ques-rep.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 ... | // except according to those terms.
// Test behavior of `?` macro _kleene op_ under the 2015 edition. Namely, it doesn't exist.
// edition:2015
macro_rules! bar {
($(a)?) => {} //~ERROR expected `*` or `+`
}
macro_rules! baz {
($(a),?) => {} //~ERROR expected `*` or `+`
}
fn main() {} | // option. This file may not be copied, modified, or distributed | random_line_split |
macro-at-most-once-rep-2015-ques-rep.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 ... | () {}
| main | identifier_name |
macro-at-most-once-rep-2015-ques-rep.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 ... | {} | identifier_body | |
sys.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Nathan Zadoks <nathan@nathan7.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your o... | use self::std::io::Error as IoError;
use self::libc::{c_void, c_int, size_t};
use self::libc::{mmap, mprotect, munmap};
use self::libc::MAP_FAILED;
const GUARD_PROT: c_int = libc::PROT_NONE;
const STACK_PROT: c_int = libc::PROT_READ
| libc::PROT_WRITE;
#[cfg(not(any(target_os = "freebsd", ta... |
use self::std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};
use self::std::ptr; | random_line_split |
sys.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Nathan Zadoks <nathan@nathan7.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your o... | (ptr: *mut u8) -> Result<(), IoError> {
if mprotect(ptr as *mut c_void, page_size() as size_t, GUARD_PROT) == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
}
pub unsafe fn unmap_stack(ptr: *mut u8, len: usize) -> Result<(), IoError> {
if munmap(ptr as *mut c_void, len as size_t) == 0 {
Ok(())... | protect_stack | identifier_name |
sys.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) Nathan Zadoks <nathan@nathan7.eu>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your o... |
pub unsafe fn unmap_stack(ptr: *mut u8, len: usize) -> Result<(), IoError> {
if munmap(ptr as *mut c_void, len as size_t) == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
}
pub fn page_size() -> usize {
#[cold]
pub fn sys_page_size() -> usize {
unsafe {
libc::sysconf(libc::_SC_PAGES... | {
if mprotect(ptr as *mut c_void, page_size() as size_t, GUARD_PROT) == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
} | identifier_body |
mod.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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.
// Th... |
fn unregister(&mut self, addr: Address) -> Option<Box<native::Contract>> {
self.contracts.remove(&addr)
}
fn get_native_contract(&self, addr: &Address) -> Option<&Box<native::Contract>> {
self.contracts.get(addr)
}
} | }
fn register(&mut self, addr: Address, contract: Box<native::Contract>) {
self.contracts.insert(addr, contract);
} | random_line_split |
mod.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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.
// Th... |
fn get_native_contract(&self, addr: &Address) -> Option<&Box<native::Contract>> {
self.contracts.get(addr)
}
}
| {
self.contracts.remove(&addr)
} | identifier_body |
mod.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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.
// Th... | (&self) -> &BTreeMap<Address, Builtin> {
&self.builtins
}
fn register(&mut self, addr: Address, contract: Box<native::Contract>) {
self.contracts.insert(addr, contract);
}
fn unregister(&mut self, addr: Address) -> Option<Box<native::Contract>> {
self.contracts.remove(&addr)
... | builtins | identifier_name |
users.rs | #[allow(unused_attributes)]
use rustc_serialize::json;
use client::Client;
pub struct UserService {
client: Client,
}
impl UserService {
pub fn new(c: Client) -> UserService {
UserService { client: c }
}
pub fn get(self, name: &str) -> User {
let mut url = "https://api.github.com/us... | pub public_repos: i32,
pub public_gists: i32,
pub followers: i32,
pub following: i32,
pub created_at: String,
pub updated_at: String,
} | pub bio: Option<String>, | random_line_split |
users.rs | #[allow(unused_attributes)]
use rustc_serialize::json;
use client::Client;
pub struct | {
client: Client,
}
impl UserService {
pub fn new(c: Client) -> UserService {
UserService { client: c }
}
pub fn get(self, name: &str) -> User {
let mut url = "https://api.github.com/users/".to_string();
url.push_str(name);
let req = self.client.request(url.as_slice(... | UserService | identifier_name |
flow_control_table.rs | // SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
use super::super::super::FlowControl;
use std::collections::HashMap;
lazy_static! {
pub(super) static ref TO_FLOW_CONTROL_HASH: HashMap<&'static str, FlowControl> = {
// GENERATOR-BEGIN: FlowControlHash
// ⚠️This was g... | let _ = h.insert("XbeginXabortXend", FlowControl::XbeginXabortXend);
let _ = h.insert("Exception", FlowControl::Exception);
// GENERATOR-END: FlowControlHash
h
};
} | let _ = h.insert("Call", FlowControl::Call);
let _ = h.insert("IndirectCall", FlowControl::IndirectCall);
let _ = h.insert("Interrupt", FlowControl::Interrupt); | random_line_split |
table.rs | // The MIT License (MIT)
// Copyright (c) 2014 Y. T. CHUNG <zonyitoo@gmail.com>
// 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 righ... | (&mut self, data: &[u8], out: &mut Vec<u8>) -> CipherResult<()> {
self.process(data, out)
}
fn finalize(&mut self, _: &mut Vec<u8>) -> CipherResult<()> {
Ok(())
}
}
#[test]
fn test_table_cipher() {
let message = "hello world";
let key = "keykeykk";
let mut enc = TableCipher::n... | update | identifier_name |
table.rs | // The MIT License (MIT)
// Copyright (c) 2014 Y. T. CHUNG <zonyitoo@gmail.com>
// 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 righ... | dec.update(&encrypted_msg[..], &mut decrypted_msg).unwrap();
assert_eq!(&decrypted_msg[..], message.as_bytes());
} | random_line_split | |
table.rs | // The MIT License (MIT)
// Copyright (c) 2014 Y. T. CHUNG <zonyitoo@gmail.com>
// 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 righ... | unsafe { t.set_len(table.len()); }
for idx in 0..table.len() {
t[table[idx] as usize] = idx as u8;
}
t
}
},
}
}
fn process(&mut self, data: &[u8], out: &mut Vec<u8>) -> C... | {
let mut md5_digest = digest::with_type(DigestType::Md5);
md5_digest.update(key);
let key_digest = md5_digest.digest();
let mut bufr = BufReader::new(&key_digest[..]);
let a = bufr.read_u64::<LittleEndian>().unwrap();
let mut table = (0..TABLE_SIZE).map(|idx| idx as u64... | identifier_body |
sync.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) {
self.channels.fetch_add(1, atomic::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, atomic::SeqCst) {
1 => {}
_ => return
}
// Not much to do other ... | clone_chan | identifier_name |
sync.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 ... | }
} else {
None
};
mem::drop((state, guard));
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.wake().map(|t| t.reawaken()));
pending_sender2.map(|t| t.wake().map(|t| t.reawaken()));
}
// Prepares this... | } | random_line_split |
sync.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 ... | else {
None
};
mem::drop((state, guard));
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.wake().map(|t| t.reawaken()));
pending_sender2.map(|t| t.wake().map(|t| t.reawaken()));
}
// Prepares this shared packet for a ch... | {
match mem::replace(&mut state.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(task) => {
state.canceled.take();
Some(task)
}
}
} | conditional_block |
euler_5.rs | /***********
Problem 5:
|
// const Small_primes:Vec<u32> = [2,3,5,7,11,13,17,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101; 25];
//
// // fn decomposition(num: u64) -> Vec<u64> {
// // Small_primes
// // }
//
// pub fn answer() {
// let mut result = 0u64;
//
//
// // decomposition(40);
// println!("result; {}", result... | 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
***********/ | random_line_split |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::CSSStyleRuleMethods;
use crate::dom::bindings::... | .cssrule
.parent_stylesheet()
.style_stylesheet()
.contents
.namespaces
.read();
let parser = SelectorParser {
stylesheet_origin: Origin::Author,
namespaces: &namespaces,
url_data: None,
};
let ... | // It's not clear from the spec if we should use the stylesheet's namespaces.
// https://github.com/w3c/csswg-drafts/issues/1511
let namespaces = self | random_line_split |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::CSSStyleRuleMethods;
use crate::dom::bindings::... |
}
}
}
| {
stylesheets_owner_from_node(owner.upcast::<Node>()).invalidate_stylesheets();
} | conditional_block |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::CSSStyleRuleMethods;
use crate::dom::bindings::... | (
window: &Window,
parent_stylesheet: &CSSStyleSheet,
stylerule: Arc<Locked<StyleRule>>,
) -> DomRoot<CSSStyleRule> {
reflect_dom_object(
Box::new(CSSStyleRule::new_inherited(parent_stylesheet, stylerule)),
window,
)
}
}
impl SpecificCSSRule for C... | new | identifier_name |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::CSSStyleRuleMethods;
use crate::dom::bindings::... |
fn get_css(&self) -> DOMString {
let guard = self.cssrule.shared_lock().read();
self.stylerule
.read_with(&guard)
.to_css_string(&guard)
.into()
}
}
impl CSSStyleRuleMethods for CSSStyleRule {
// https://drafts.csswg.org/cssom/#dom-cssstylerule-style
f... | {
use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
} | identifier_body |
package.rs | use std::cmp;
use std::fmt::{Show,Formatter};
use std::fmt;
use std::slice;
use semver::Version;
use core::{
Dependency,
Manifest,
PackageId,
Registry,
Target,
Summary
};
use core::dependency::SerializedDependency;
use util::{CargoResult, graph, Config};
use serialize::{Encoder,Encodable};
use ... | (&self, names: &[&str]) -> Vec<&Package> {
names.iter().map(|name| self.get(*name) ).collect()
}
pub fn get_packages(&self) -> &[Package] {
self.packages.as_slice()
}
// For now, assume that the package set contains only one package with a
// given name
pub fn sort(&self) -> Op... | get_all | identifier_name |
package.rs | use std::cmp;
use std::fmt::{Show,Formatter};
use std::fmt;
use std::slice;
use semver::Version;
use core::{
Dependency,
Manifest,
PackageId,
Registry,
Target,
Summary
};
use core::dependency::SerializedDependency;
use util::{CargoResult, graph, Config};
use serialize::{Encoder,Encodable};
use ... |
pub fn get_version(&self) -> &Version {
self.get_package_id().get_version()
}
pub fn get_dependencies(&self) -> &[Dependency] {
self.get_manifest().get_dependencies()
}
pub fn get_targets(&self) -> &[Target] {
self.get_manifest().get_targets()
}
pub fn get_manife... | {
self.get_package_id().get_name()
} | identifier_body |
package.rs | use std::cmp;
use std::fmt::{Show,Formatter};
use std::fmt;
use std::slice;
use semver::Version;
use core::{
Dependency,
Manifest,
PackageId,
Registry,
Target,
Summary
};
use core::dependency::SerializedDependency;
use util::{CargoResult, graph, Config};
use serialize::{Encoder,Encodable};
use ... | impl PartialEq for Package {
fn eq(&self, other: &Package) -> bool {
self.get_package_id() == other.get_package_id()
}
}
#[deriving(PartialEq,Clone,Show)]
pub struct PackageSet {
packages: Vec<Package>,
}
impl PackageSet {
pub fn new(packages: &[Package]) -> PackageSet {
//assert!(pack... | fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.get_summary().get_package_id())
}
}
| random_line_split |
os_str.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl Buf {
pub fn from_string(s: String) -> Buf {
Buf { inner: s.into_bytes() }
}
pub fn from_str(s: &str) -> Buf {
Buf { inner: s.as_bytes().to_vec() }
}
pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(&*self.inner) }
}
pub fn into_string(self) -> R... | {
self.as_slice().fmt(formatter)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.