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 |
|---|---|---|---|---|
build.rs | extern crate cc;
extern crate bindgen;
use std::env;
use std::fs;
use std::path::PathBuf;
fn link(name: &str, bundled: bool) {
use std::env::var;
let target = var("TARGET").unwrap();
let target: Vec<_> = target.split('-').collect();
if target.get(2) == Some(&"windows") {
println!("cargo:rustc-... |
if cfg!(target_os = "linux") {
config.define("OS_LINUX", Some("1"));
config.define("ROCKSDB_PLATFORM_POSIX", Some("1"));
config.define("ROCKSDB_LIB_IO_POSIX", Some("1"));
// COMMON_FLAGS="$COMMON_FLAGS -fno-builtin-memcmp"
}
if cfg!(target_os = "freebsd") {
config.de... | {
config.define("OS_MACOSX", Some("1"));
config.define("ROCKSDB_PLATFORM_POSIX", Some("1"));
config.define("ROCKSDB_LIB_IO_POSIX", Some("1"));
} | conditional_block |
build.rs | extern crate cc;
extern crate bindgen;
use std::env;
use std::fs;
use std::path::PathBuf;
fn link(name: &str, bundled: bool) {
use std::env::var;
let target = var("TARGET").unwrap();
let target: Vec<_> = target.split('-').collect();
if target.get(2) == Some(&"windows") {
println!("cargo:rustc-... | config.flag("-Wno-unused-parameter");
}
for file in lib_sources {
let file = "rocksdb/".to_string() + file;
config.file(&file);
}
config.file("build_version.cc");
config.cpp(true);
config.compile("librocksdb.a");
}
fn build_snappy() {
let mut config = cc::Build::n... | config.flag("-EHsc");
} else {
config.flag("-std=c++11");
// this was breaking the build on travis due to
// > 4mb of warnings emitted. | random_line_split |
build.rs | extern crate cc;
extern crate bindgen;
use std::env;
use std::fs;
use std::path::PathBuf;
fn link(name: &str, bundled: bool) {
use std::env::var;
let target = var("TARGET").unwrap();
let target: Vec<_> = target.split('-').collect();
if target.get(2) == Some(&"windows") {
println!("cargo:rustc-... | () {
let mut config = cc::Build::new();
config.include("snappy/");
config.include(".");
config.define("NDEBUG", Some("1"));
if cfg!(target_env = "msvc") {
config.flag("-EHsc");
} else {
config.flag("-std=c++11");
}
config.file("snappy/snappy.cc");
config.file("snap... | build_snappy | identifier_name |
build.rs | extern crate cc;
extern crate bindgen;
use std::env;
use std::fs;
use std::path::PathBuf;
fn link(name: &str, bundled: bool) {
use std::env::var;
let target = var("TARGET").unwrap();
let target: Vec<_> = target.split('-').collect();
if target.get(2) == Some(&"windows") {
println!("cargo:rustc-... | .collect::<Vec<&'static str>>();
if cfg!(target_os = "macos") {
config.define("OS_MACOSX", Some("1"));
config.define("ROCKSDB_PLATFORM_POSIX", Some("1"));
config.define("ROCKSDB_LIB_IO_POSIX", Some("1"));
}
if cfg!(target_os = "linux") {
config.define("OS_LINUX", Som... | {
let mut config = cc::Build::new();
config.include("rocksdb/include/");
config.include("rocksdb/");
config.include("rocksdb/third-party/gtest-1.7.0/fused-src/");
config.include("snappy/");
config.include(".");
config.define("NDEBUG", Some("1"));
config.define("SNAPPY", Some("1"));
... | identifier_body |
tests.rs | use super::*;
use rustc_data_structures::sync::Lrc;
fn init_source_map() -> SourceMap {
let sm = SourceMap::new(FilePathMapping::empty());
sm.new_source_file(PathBuf::from("blork.rs").into(), "first line.\nsecond line".to_string());
sm.new_source_file(PathBuf::from("empty.rs").into(), String::new());
... |
fn init_source_map_mbc() -> SourceMap {
let sm = SourceMap::new(FilePathMapping::empty());
// "€" is a three-byte UTF8 char.
sm.new_source_file(
PathBuf::from("blork.rs").into(),
"fir€st €€€€ line.\nsecond line".to_string(),
);
sm.new_source_file(
PathBuf::from("blork2.rs")... | {
let sm = init_source_map();
let loc1 = sm.lookup_char_pos(BytePos(22));
assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
assert_eq!(loc1.line, 2);
assert_eq!(loc1.col, CharPos(10));
let loc2 = sm.lookup_char_pos(BytePos(25));
assert_eq!(loc2.file.name, PathBuf::from("blork2.... | identifier_body |
tests.rs | use super::*;
use rustc_data_structures::sync::Lrc;
fn init_source_map() -> SourceMap {
let sm = SourceMap::new(FilePathMapping::empty());
sm.new_source_file(PathBuf::from("blork.rs").into(), "first line.\nsecond line".to_string());
sm.new_source_file(PathBuf::from("empty.rs").into(), String::new());
... | assert_eq!(cp1, CharPos(22));
let cp2 = sm.bytepos_to_file_charpos(BytePos(25));
assert_eq!(cp2, CharPos(0));
}
/// Tests zero-length `SourceFile`s.
#[test]
fn t5() {
let sm = init_source_map();
let loc1 = sm.lookup_char_pos(BytePos(22));
assert_eq!(loc1.file.name, PathBuf::from("blork.rs").i... |
let cp1 = sm.bytepos_to_file_charpos(BytePos(22)); | random_line_split |
tests.rs | use super::*;
use rustc_data_structures::sync::Lrc;
fn init_source_map() -> SourceMap {
let sm = SourceMap::new(FilePathMapping::empty());
sm.new_source_file(PathBuf::from("blork.rs").into(), "first line.\nsecond line".to_string());
sm.new_source_file(PathBuf::from("empty.rs").into(), String::new());
... | init_source_map();
let span = Span::with_root_ctxt(BytePos(12), BytePos(23));
let snippet = sm.span_to_snippet(span);
assert_eq!(snippet, Ok("second line".to_string()));
}
/// Test `span_to_str` for a span ending at the end of a `SourceFile`.
#[test]
fn t9() {
let sm = init_source_map();
let span ... | = | identifier_name |
result.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #[test]
pub fn test_impl_map_err() {
assert_eq!(Ok::<~str, ~str>(~"a").map_err(|_x| ~"b"), Ok(~"a"));
assert_eq!(Err::<~str, ~str>(~"a").map_err(|_x| ~"b"), Err(~"b"));
}
#[test]
pub fn test_get_ref_method() {
let foo: Result<int, ()> = Ok(100);
assert_eq!(*foo.get_r... | }
| random_line_split |
result.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 ... | <T:Copy,U:Copy>(res: &Result<U, T>)
-> Either<T, U> {
match *res {
Ok(ref res) => either::Right(copy *res),
Err(ref fail_) => either::Left(copy *fail_)
}
}
/**
* Call a function based on a previous result
*
* If `res` is `ok` then the value is extracted and passed to `op` whereupon
* `op`s ... | to_either | identifier_name |
result.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
| {
let foo: Result<int, ()> = Ok(100);
assert_eq!(*foo.get_ref(), 100);
} | identifier_body |
boxed-class-type-substitution.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 |
boxed-class-type-substitution.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 ... |
struct Box {
tree: Tree<@Box>
}
fn Box() -> Box {
Box {
tree: empty()
}
}
struct LayoutData {
box: Option<@Box>
}
pub fn main() { }
| { fail!() } | identifier_body |
boxed-class-type-substitution.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// 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.
// Regression te... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
tests.rs | use parking_lot;
use rand;
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use boxfuture::{BoxFuture, Boxable};
use futures01::future::{self, Future};
use hashing::Digest;
use parking_lot::Mutex;
use rand::Rng;
use crate::{EntryId, Graph,... |
fn with_salt(mut self, salt: usize) -> TContext {
self.salt = salt;
self
}
fn new_session(mut self, new_session_id: usize) -> TContext {
self.session_id = new_session_id;
{
let mut runs = self.runs.lock();
runs.clear();
}
self
}
fn salt(&self) -> usize {
self.salt
... | {
self.uncacheable = Arc::new(uncacheable);
self
} | identifier_body |
tests.rs | use parking_lot;
use rand;
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use boxfuture::{BoxFuture, Boxable};
use futures01::future::{self, Future};
use hashing::Digest;
use parking_lot::Mutex;
use rand::Rng;
use crate::{EntryId, Graph,... | }
fn with_delays(mut self, delays: HashMap<TNode, Duration>) -> TContext {
self.delays = Arc::new(delays);
self
}
fn with_uncacheable(mut self, uncacheable: HashSet<TNode>) -> TContext {
self.uncacheable = Arc::new(uncacheable);
self
}
fn with_salt(mut self, salt: usize) -> TContext {
... | fn with_dependencies(mut self, edges: HashMap<TNode, Option<TNode>>) -> TContext {
self.edges = Arc::new(edges);
self | random_line_split |
tests.rs | use parking_lot;
use rand;
use std::cmp;
use std::collections::{HashMap, HashSet};
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
use boxfuture::{BoxFuture, Boxable};
use futures01::future::{self, Future};
use hashing::Digest;
use parking_lot::Mutex;
use rand::Rng;
use crate::{EntryId, Graph,... | () {
use super::entry::Entry;
// First, let's describe the scenario with plain data.
//
// We label the nodes with static strings to help visualise the situation.
// The first element of each tuple is a readable label. The second element represents the
// duration for this action.
let nodes = [
("down... | critical_path | identifier_name |
ast_util.rs | match b {
and => true,
or => true,
_ => false
}
}
pub fn is_shift_binop(b: binop) -> bool {
match b {
shl => true,
shr => true,
_ => false
}
}
pub fn unop_to_str(op: unop) -> ~str {
match op {
box(mt) => if mt == m_mutbl { ~"@mut " } else { ~"@" },
uni... | (&self, lsb0: bool, f: to_bytes::Cb) -> bool {
to_bytes::iter_bytes_2(&self.crate, &self.node, lsb0, f)
}
}
pub fn block_from_expr(e: @expr) -> blk {
let blk_ = default_block(~[], option::Some::<@expr>(e), e.id);
return spanned {node: blk_, span: e.span};
}
pub fn default_block(
stmts1: ~[@stm... | iter_bytes | identifier_name |
ast_util.rs |
pub fn def_id_of_def(d: def) -> def_id {
match d {
def_fn(id, _) | def_static_method(id, _, _) | def_mod(id) |
def_foreign_mod(id) | def_const(id) |
def_variant(_, id) | def_ty(id) | def_ty_param(id, _) |
def_use(id) | def_struct(id) | def_trait(id) => {
id
}
def_arg(id... | {
match d {
def_variant(enum_id, var_id) => {
Some((enum_id, var_id))
}
_ => None
}
} | identifier_body | |
ast_util.rs | match b {
and => true,
or => true,
_ => false
}
}
pub fn is_shift_binop(b: binop) -> bool {
match b {
shl => true,
shr => true,
_ => false
}
}
pub fn unop_to_str(op: unop) -> ~str {
match op {
box(mt) => if mt == m_mutbl { ~"@mut " } else { ~"@" },
un... | }
}
}
}
/// Push a name... unless it matches the one on top, in which
/// case pop and discard (so two of the same marks cancel)
pub fn xorPush(marks: &mut ~[uint], mark: uint) {
if ((marks.len() > 0) && (getLast(marks) == mark)) {
marks.pop();
} else {
marks.push(mark);... | if (name == stopname) {
return result;
} else {
loopvar = tl;
} | random_line_split |
level_bar.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | self) -> bool {
unsafe { to_bool(ffi::gtk_level_bar_get_inverted(GTK_LEVELBAR(self.pointer))) }
}
pub fn add_offset_value(&mut self, name: &str, value: f64) -> () {
unsafe {
ffi::gtk_level_bar_add_offset_value(
GTK_LEVELBAR(self.pointer),
name.borrow_... | t_inverted(& | identifier_name |
level_bar.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | pub fn set_mode(&mut self, mode: LevelBarMode) -> () {
unsafe {
ffi::gtk_level_bar_set_mode(GTK_LEVELBAR(self.pointer), mode);
}
}
pub fn get_mode(&self) -> LevelBarMode {
unsafe {
ffi::gtk_level_bar_get_mode(GTK_LEVELBAR(self.pointer))
}
}
p... | unsafe {
ffi::gtk_level_bar_get_value(GTK_LEVELBAR(self.pointer)) as f64
}
}
| identifier_body |
level_bar.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
use libc::c_double;
use glib::translate::ToGlibPtr;
use gtk::{self, ffi};
use glib::{to_bool, to_gboolean};
use gtk::{LevelBarMode};
use gtk::cast::GTK_LEVELBAR;
/// LevelBar — A bar that can used as a level indicator
/*
* # Signal availables:
* * `offset-changed` : Has Details
*/
struct_Widget!(LevelBar);
impl Lev... |
//! A bar that can used as a level indicator
#![cfg_attr(not(feature = "GTK_3_8"), allow(unused_imports))] | random_line_split |
level_bar.rs | // This file is part of rgtk.
//
// rgtk 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 Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | else {
None
}
}
}
}
impl_drop!(LevelBar);
impl_TraitWidget!(LevelBar);
impl gtk::OrientableTrait for LevelBar {}
impl_widget_events!(LevelBar);
| Some(value)
}
| conditional_block |
helpers.rs | #[derive(Debug)]
pub enum Entry {
// either a unique page and its link data
Page {
title: String,
children: Vec<u32>,
parents: Vec<u32>,
},
// or the redirect page and its address
// these will eventually be taken out of db::entries
Redirect {
title: String,
... | #[derive(PartialEq, PartialOrd, Debug)]
pub enum State {
Begin = 0,
AddPages = 1,
AddRedirects = 2,
TidyEntries = 3,
AddLinks = 4,
Done = 5,
} | // their inequality; here concrete values make it clearer | random_line_split |
helpers.rs |
#[derive(Debug)]
pub enum | {
// either a unique page and its link data
Page {
title: String,
children: Vec<u32>,
parents: Vec<u32>,
},
// or the redirect page and its address
// these will eventually be taken out of db::entries
Redirect {
title: String,
target: Option<u32>,
}
}... | Entry | identifier_name |
counter.rs | use sfml::graphics::*;
use sfml::system::{Vector2f, Vector2u};
use resize_handler::ResizeHandler; | const OFFSET: Vector2f = Vector2f { x: 32., y: 32. };
pub struct Counter<'s> {
icon: Sprite<'s>,
text: Text<'s>,
rel_pos: Vector2f,
}
impl<'s> Counter<'s> {
pub fn new(tex: &'s TextureRef, font: &'s Font, rel_pos: &Vector2f) -> Counter<'s> {
Counter {
icon: Sprite::with_texture(tex... | use super::element::*;
| random_line_split |
counter.rs | use sfml::graphics::*;
use sfml::system::{Vector2f, Vector2u};
use resize_handler::ResizeHandler;
use super::element::*;
const OFFSET: Vector2f = Vector2f { x: 32., y: 32. };
pub struct Counter<'s> {
icon: Sprite<'s>,
text: Text<'s>,
rel_pos: Vector2f,
}
impl<'s> Counter<'s> {
pub fn new(tex: &'s Tex... |
}
| {
self.rel_pos = *pos;
self.recalculate(win_size.x, win_size.y);
} | identifier_body |
counter.rs | use sfml::graphics::*;
use sfml::system::{Vector2f, Vector2u};
use resize_handler::ResizeHandler;
use super::element::*;
const OFFSET: Vector2f = Vector2f { x: 32., y: 32. };
pub struct Counter<'s> {
icon: Sprite<'s>,
text: Text<'s>,
rel_pos: Vector2f,
}
impl<'s> Counter<'s> {
pub fn new(tex: &'s Tex... | (&mut self, win_width: u32, win_height: u32) {
self.icon.set_position2f(win_width as f32 * self.rel_pos.x,
win_height as f32 * self.rel_pos.y);
let bounds = self.icon.global_bounds();
self.text.set_position2f(bounds.left, bounds.top);
self.text.move_(&OF... | recalculate | identifier_name |
polygon.rs | //! Draw polygon
use crate::{
math::{Matrix2d, Scalar},
triangulation, types,
types::Color,
DrawState, Graphics,
};
/// A polygon
#[derive(Copy, Clone)]
pub struct Polygon {
/// The color of the polygon
pub color: Color,
}
impl Polygon {
/// Creates new polygon
pub fn new(color: Color... |
g.tri_list(draw_state, &self.color, |f| {
triangulation::with_lerp_polygons_tri_list(
transform,
polygons,
tween_factor,
|vertices| f(vertices),
)
});
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
... | {
return;
} | conditional_block |
polygon.rs | //! Draw polygon
use crate::{
math::{Matrix2d, Scalar},
triangulation, types,
types::Color,
DrawState, Graphics,
};
/// A polygon
#[derive(Copy, Clone)]
pub struct Polygon {
/// The color of the polygon
pub color: Color,
}
impl Polygon {
/// Creates new polygon
pub fn new(color: Color... | <G>(
&self,
polygon: types::Polygon<'_>,
draw_state: &DrawState,
transform: Matrix2d,
g: &mut G,
) where
G: Graphics,
{
g.tri_list(draw_state, &self.color, |f| {
triangulation::with_polygon_tri_list(transform, polygon, |vertices| f(vertices))
... | draw_tri | identifier_name |
polygon.rs | //! Draw polygon
use crate::{
math::{Matrix2d, Scalar},
triangulation, types,
types::Color,
DrawState, Graphics,
};
/// A polygon
#[derive(Copy, Clone)]
pub struct Polygon {
/// The color of the polygon
pub color: Color,
}
impl Polygon {
/// Creates new polygon
pub fn new(color: Color... |
/// Sets color.
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
/// Draws polygon using the default method.
#[inline(always)]
pub fn draw<G>(
&self,
polygon: types::Polygon<'_>,
draw_state: &DrawState,
transform: Matrix... | {
Polygon { color }
} | identifier_body |
polygon.rs | //! Draw polygon
use crate::{
math::{Matrix2d, Scalar},
triangulation, types,
types::Color,
DrawState, Graphics,
};
/// A polygon
#[derive(Copy, Clone)]
pub struct Polygon {
/// The color of the polygon
pub color: Color,
}
impl Polygon {
/// Creates new polygon
pub fn new(color: Color... | }
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_polygon() {
let _polygon = Polygon::new([1.0; 4]).color([0.0; 4]);
}
} | |vertices| f(vertices),
)
});
} | random_line_split |
TranslationCache.rs | extern crate libc;
use std::mem;
use std::marker;
use std::ops::{Index, IndexMut};
extern{
fn memset(s: *mut libc::c_void, c: libc::uint32_t, n: libc::size_t) -> *mut libc::c_void;
}
pub struct TranslationCache {
pub page : *mut u8
}
unsafe impl Send for TranslationCache {}
unsafe impl Sync for TranslationC... | (num_pages: usize) -> TranslationCache {
let page : *mut u8;
unsafe {
let cache_size = num_pages * PAGE_SIZE;
let mut _page : *mut libc::c_void = mem::uninitialized();
libc::posix_memalign(&mut _page, PAGE_SIZE, cache_size);
libc::mprotect(_page, cache_siz... | new | identifier_name |
TranslationCache.rs | extern crate libc;
use std::mem;
use std::marker;
use std::ops::{Index, IndexMut};
extern{
fn memset(s: *mut libc::c_void, c: libc::uint32_t, n: libc::size_t) -> *mut libc::c_void;
}
pub struct TranslationCache {
pub page : *mut u8
}
unsafe impl Send for TranslationCache {}
unsafe impl Sync for TranslationC... | impl IndexMut<usize> for TranslationCache {
fn index_mut(&mut self, _index: usize) -> &mut u8 {
unsafe {&mut *self.page.offset(_index as isize) }
}
}
impl TranslationCache {
pub fn new(num_pages: usize) -> TranslationCache {
let page : *mut u8;
unsafe {
let cache_size = ... | }
}
| random_line_split |
main.rs | fn main() {
{
// 数组实现了 Copy trait,在栈上分配的数组可以被复制
let mut arr = [1,2,3,4];
let mut arr2 = arr; // arr2 是 arr 的拷贝并不是原有数据
arr[0] = 100;
arr2[0] = 200;
println!("arr: {:?}, arr2: {:?}", arr, arr2);
}
{
// 堆上分配的数组不能被复制
let arr = Box::new([1,2,3,4]);
... | r: {:?}", arr);
}
| intln!("ar | identifier_name |
main.rs | fn main() {
{
// 数组实现了 Copy trait,在栈上分配的数组可以被复制
let mut arr = [1,2,3,4];
let mut arr2 = arr; // arr2 是 arr 的拷贝并不是原有数据
arr[0] = 100;
arr2[0] = 200;
println!("arr: {:?}, arr2: {:?}", arr, arr2);
}
{
// 堆上分配的数组不能被复制
let arr = Box::new([1,2,3,4]);
... | }
| identifier_body | |
main.rs | fn main() {
{ | println!("arr: {:?}, arr2: {:?}", arr, arr2);
}
{
// 堆上分配的数组不能被复制
let arr = Box::new([1,2,3,4]);
let arr2 = arr; // arr 所有权转移给 arr2
// println!("arr: {:?}", arr); // 失败
println!("arr2: {:?}", arr2);
}
{
let arr = Box::new([1,2,3,4]);
{
... | // 数组实现了 Copy trait,在栈上分配的数组可以被复制
let mut arr = [1,2,3,4];
let mut arr2 = arr; // arr2 是 arr 的拷贝并不是原有数据
arr[0] = 100;
arr2[0] = 200; | random_line_split |
signalargs.rs | use arg;
use {Message, MessageType, BusName, Path, Interface, Member};
/// Helper methods for structs representing a Signal
///
/// # Example
///
/// Listen to InterfacesRemoved signal from org.bluez.obex.
///
/// ```rust,no_run
/// use dbus::{Connection, ConnectionItem, BusType, SignalArgs};
/// use dbus::stdintf::Or... | if m.msg_type()!= MessageType::Signal { None }
else if m.interface().as_ref().map(|x| &**x)!= Some(Self::INTERFACE) { None }
else if m.member().as_ref().map(|x| &**x)!= Some(Self::NAME) { None }
else {
let mut z: Self = Default::default();
z.get(&mut m.iter_init()... | random_line_split | |
signalargs.rs | use arg;
use {Message, MessageType, BusName, Path, Interface, Member};
/// Helper methods for structs representing a Signal
///
/// # Example
///
/// Listen to InterfacesRemoved signal from org.bluez.obex.
///
/// ```rust,no_run
/// use dbus::{Connection, ConnectionItem, BusType, SignalArgs};
/// use dbus::stdintf::Or... | (&self, path: &Path) -> Message {
let mut m = Message::signal(path, &Interface::from(Self::INTERFACE), &Member::from(Self::NAME));
self.append(&mut arg::IterAppend::new(&mut m));
m
}
/// If the message is a signal of the correct type, return its arguments, otherwise return None.
///... | to_emit_message | identifier_name |
signalargs.rs | use arg;
use {Message, MessageType, BusName, Path, Interface, Member};
/// Helper methods for structs representing a Signal
///
/// # Example
///
/// Listen to InterfacesRemoved signal from org.bluez.obex.
///
/// ```rust,no_run
/// use dbus::{Connection, ConnectionItem, BusType, SignalArgs};
/// use dbus::stdintf::Or... |
/// If the message is a signal of the correct type, return its arguments, otherwise return None.
///
/// This does not check sender and path of the message, which is likely relevant to you as well.
fn from_message(m: &Message) -> Option<Self> {
if m.msg_type()!= MessageType::Signal { None }
... | {
let mut m = Message::signal(path, &Interface::from(Self::INTERFACE), &Member::from(Self::NAME));
self.append(&mut arg::IterAppend::new(&mut m));
m
} | identifier_body |
log.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: shared/log/log.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A general logging collection
with differen verbosity levels.
Use Q3_LOG=num ... | {
let logger = Log::get();
log_assert!(logger.push_level > 0);
logger.push_level -= 1;
}
fn log(module: &str, message: &str, verbosity: Verbosity)
{
let logger = Log::get();
/* Allow the listener to intervene. */
let log_to_stdout = match logger.listener
{
Some(ref mut liste... | random_line_split | |
log.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: shared/log/log.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A general logging collection
with differen verbosity levels.
Use Q3_LOG=num ... | (module: &str, message: &str)
{
let logger = Log::get();
if logger.verbosity >= VERBOSITY_INFO
{ Log::log(module, message, VERBOSITY_INFO); }
}
pub fn error(module: &str, message: &str)
{
let logger = Log::get();
if logger.verbosity >= VERBOSITY_ERROR
{ Log::log(module, message, VERBOSI... | info | identifier_name |
log.rs | /*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: shared/log/log.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
A general logging collection
with differen verbosity levels.
Use Q3_LOG=num ... |
fn log(module: &str, message: &str, verbosity: Verbosity)
{
let logger = Log::get();
/* Allow the listener to intervene. */
let log_to_stdout = match logger.listener
{
Some(ref mut listener) =>
{ (*listener).log(module, message, verbosity) }
None => { true },
};
if!log_t... | {
let logger = Log::get();
log_assert!(logger.push_level > 0);
logger.push_level -= 1;
} | identifier_body |
extensions.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 canvas_traits::webgl::WebGLError;
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings:... | else {
None
}
})
}
pub fn get_dom_object<T>(&self) -> Option<Root<T::Extension>>
where T:'static + WebGLExtension + JSTraceable + HeapSizeOf {
let name = T::name().to_uppercase();
self.extensions.borrow().get(&name).and_then(|extension| {
... | {
Some(extension.instance_or_init(ctx, self))
} | conditional_block |
extensions.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 canvas_traits::webgl::WebGLError;
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings:... | (&self,
source_internal_format: u32,
source_data_type: u32) -> u32 {
let format = TexFormatType(source_internal_format, source_data_type);
*(self.features.borrow().effective_tex_internal_formats.get(&format)
... | get_effective_tex_internal_format | identifier_name |
extensions.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 canvas_traits::webgl::WebGLError;
use core::iter::FromIterator;
use core::nonzero::NonZero;
use dom::bindings:... |
pub fn add_effective_tex_internal_format(&self,
source_internal_format: u32,
source_data_type: u32,
effective_internal_format: u32)
{
let format = TexFormatType(source_... | pub fn is_tex_type_enabled(&self, data_type: GLenum) -> bool {
self.features.borrow().disabled_tex_types.get(&data_type).is_none()
} | random_line_split |
char.rs | // Copyright 2012-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... | (&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
fn to_lowercase(&self) -> char { to_lowercase(*self) }
fn to_uppercase(&self) -> char { to_uppercase(*self) }
fn from_digit(num: uint, radix: uint) -> Option<char> { from_digit(num, radix) }
fn escape_unicode(&self, f: |char|) { escape_... | to_digit | identifier_name |
char.rs | // Copyright 2012-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... | 2
}
}
} | // Supplementary planes break into surrogates.
assert!(ch >= 0x1_0000_u32 && ch <= 0x10_FFFF_u32);
ch -= 0x1_0000_u32;
dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16); | random_line_split |
char.rs | // Copyright 2012-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... |
'\n' => { f('\\'); f('n'); }
'\\' => { f('\\'); f('\\'); }
'\'' => { f('\\'); f('\''); }
'"' => { f('\\'); f('"'); }
'\x20'.. '\x7e' => { f(c); }
_ => c.escape_unicode(f),
}
}
/// Returns the amount of bytes this `char` would need if encoded in UTF-8
pub fn len_utf... | { f('\\'); f('r'); } | conditional_block |
char.rs | // Copyright 2012-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... |
///
/// Indicates whether a `char` is alphanumeric
///
/// Alphanumericness is defined in terms of the Unicode General Categories
/// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
///
#[inline]
pub fn is_alphanumeric(c: char) -> bool {
derived_property::Alphabetic(c)
|| general_category::Nd... | {
// As an optimization ASCII whitespace characters are checked separately
c == ' '
|| ('\x09' <= c && c <= '\x0d')
|| property::White_Space(c)
} | identifier_body |
sccache-plus-cl.rs | use std::env;
use std::process::{self, Command};
fn main() {
let target = env::var("SCCACHE_TARGET").unwrap();
// Locate the actual compiler that we're invoking
env::set_var("CC", env::var_os("SCCACHE_CC").unwrap());
env::set_var("CXX", env::var_os("SCCACHE_CXX").unwrap());
let mut cfg = cc::Build:... | process::exit(status.code().unwrap_or(2))
} |
let status = cmd.status().expect("failed to spawn"); | random_line_split |
sccache-plus-cl.rs | use std::env;
use std::process::{self, Command};
fn | () {
let target = env::var("SCCACHE_TARGET").unwrap();
// Locate the actual compiler that we're invoking
env::set_var("CC", env::var_os("SCCACHE_CC").unwrap());
env::set_var("CXX", env::var_os("SCCACHE_CXX").unwrap());
let mut cfg = cc::Build::new();
cfg.cargo_metadata(false)
.out_dir("/"... | main | identifier_name |
sccache-plus-cl.rs | use std::env;
use std::process::{self, Command};
fn main() {
let target = env::var("SCCACHE_TARGET").unwrap();
// Locate the actual compiler that we're invoking
env::set_var("CC", env::var_os("SCCACHE_CC").unwrap());
env::set_var("CXX", env::var_os("SCCACHE_CXX").unwrap());
let mut cfg = cc::Build:... |
let status = cmd.status().expect("failed to spawn");
process::exit(status.code().unwrap_or(2))
}
| {
for s in s.split_whitespace() {
cmd.arg(s);
}
} | conditional_block |
sccache-plus-cl.rs | use std::env;
use std::process::{self, Command};
fn main() | cmd.env(k, v);
}
for arg in env::args().skip(1) {
cmd.arg(arg);
}
if let Ok(s) = env::var("SCCACHE_EXTRA_ARGS") {
for s in s.split_whitespace() {
cmd.arg(s);
}
}
let status = cmd.status().expect("failed to spawn");
process::exit(status.code().unw... | {
let target = env::var("SCCACHE_TARGET").unwrap();
// Locate the actual compiler that we're invoking
env::set_var("CC", env::var_os("SCCACHE_CC").unwrap());
env::set_var("CXX", env::var_os("SCCACHE_CXX").unwrap());
let mut cfg = cc::Build::new();
cfg.cargo_metadata(false)
.out_dir("/")
... | identifier_body |
dynamic_lib.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
impl Drop for DynamicLibrary {
fn drop(&mut self) {
unsafe {
c::FreeLibrary(self.handle);
}
}
} | 0 => Err(io::Error::last_os_error()),
n => Ok(n),
}
} | random_line_split |
dynamic_lib.rs | // Copyright 2016 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, symbol: &str) -> io::Result<usize> {
let symbol = CString::new(symbol)?;
unsafe {
match c::GetProcAddress(self.handle, symbol.as_ptr()) as usize {
0 => Err(io::Error::last_os_error()),
n => Ok(n),
}
}
}
}
impl Drop for DynamicL... | symbol | identifier_name |
dynamic_lib.rs | // Copyright 2016 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 ... |
}
| {
unsafe {
c::FreeLibrary(self.handle);
}
} | identifier_body |
run.rs | use std::old_io::process::ExitStatus;
use cargo::ops;
use cargo::core::manifest::TargetKind;
use cargo::util::{CliResult, CliError, human, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
#[derive(RustcDecodable)]
struct Options {
flag_bin: Option<String>,
flag_example: Option<String>,... | (options: Options, config: &Config) -> CliResult<Option<()>> {
config.shell().set_verbose(options.flag_verbose);
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let env = match (options.flag_release, options.flag_example.is_some()) {
(true, _) => "release",
(false, ... | execute | identifier_name |
run.rs | use std::old_io::process::ExitStatus;
use cargo::ops;
use cargo::core::manifest::TargetKind;
use cargo::util::{CliResult, CliError, human, Config};
use cargo::util::important_paths::{find_root_manifest_for_cwd};
#[derive(RustcDecodable)]
struct Options {
flag_bin: Option<String>,
flag_example: Option<String>,... | --example NAME Name of the example target to run
-j N, --jobs N The number of jobs to run in parallel
--release Build artifacts in release mode, with optimizations
--features FEATURES Space-separated list of features to also build
--no-default-features Do not bu... | --bin NAME Name of the bin target to run | random_line_split |
issue-3389.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct trie_node... | random_line_split | |
issue-3389.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 ... | {
content: ~[~str],
children: ~[trie_node],
}
fn print_str_vector(vector: ~[~str]) {
for vector.iter().advance |string| {
println(*string);
}
}
pub fn main() {
let mut node: trie_node = trie_node {
content: ~[],
children: ~[]
};
let v = ~[~"123", ~"abc"];
node.... | trie_node | identifier_name |
set_value.rs | #![allow(dead_code)]
#![allow(unused_imports)]
extern crate libc;
extern crate sysctl;
// Import the trait
use sysctl::Sysctl;
#[cfg(target_os = "freebsd")]
const CTLNAME: &str = "net.inet.ip.forwarding";
#[cfg(target_os = "macos")]
const CTLNAME: &str = "net.inet.ip.forwarding";
#[cfg(any(target_os = "linux", tar... | () {
assert_eq!(
unsafe { libc::geteuid() },
0,
"This example must be run as root"
);
let ctl = sysctl::Ctl::new(CTLNAME).expect(&format!("could not get sysctl '{}'", CTLNAME));
let name = ctl.name().expect("could not get sysctl name");
println!("\nFlipping value of sysctl ... | main | identifier_name |
set_value.rs | #![allow(dead_code)]
#![allow(unused_imports)]
extern crate libc;
extern crate sysctl;
// Import the trait
use sysctl::Sysctl;
#[cfg(target_os = "freebsd")]
const CTLNAME: &str = "net.inet.ip.forwarding";
#[cfg(target_os = "macos")]
const CTLNAME: &str = "net.inet.ip.forwarding";
#[cfg(any(target_os = "linux", tar... | println!("Setting value to '{}'...", target_value);
let new_value = ctl.set_value_string(target_value).unwrap_or_else(|e| {
panic!("Could not set value. Error: {:?}", e);
});
assert_eq!(new_value, target_value, "could not set value");
println!("OK. Now restoring old value '{}'...", old_value... | {
assert_eq!(
unsafe { libc::geteuid() },
0,
"This example must be run as root"
);
let ctl = sysctl::Ctl::new(CTLNAME).expect(&format!("could not get sysctl '{}'", CTLNAME));
let name = ctl.name().expect("could not get sysctl name");
println!("\nFlipping value of sysctl '{}... | identifier_body |
set_value.rs | #![allow(dead_code)]
#![allow(unused_imports)]
extern crate libc;
extern crate sysctl;
// Import the trait
use sysctl::Sysctl;
#[cfg(target_os = "freebsd")]
const CTLNAME: &str = "net.inet.ip.forwarding";
#[cfg(target_os = "macos")]
const CTLNAME: &str = "net.inet.ip.forwarding";
#[cfg(any(target_os = "linux", tar... | let new_value = ctl.set_value_string(target_value).unwrap_or_else(|e| {
panic!("Could not set value. Error: {:?}", e);
});
assert_eq!(new_value, target_value, "could not set value");
println!("OK. Now restoring old value '{}'...", old_value);
let ret = ctl
.set_value_string(&old_valu... | "0" => "1",
_ => "0",
};
println!("Setting value to '{}'...", target_value); | random_line_split |
issue-7911.rs | // Copyright 2012-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... | { bar: Bar }
impl FooBar for Bar {}
trait Test {
fn get_immut(&self) -> &FooBar;
fn get_mut(&mut self) -> &mut FooBar;
}
macro_rules! generate_test { ($type_:path, $slf:ident, $field:expr) => (
impl Test for $type_ {
fn get_immut(&$slf) -> &FooBar {
&$field as &FooBar
}
... | Foo | identifier_name |
issue-7911.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-pretty
/... | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split | |
issue-7911.rs | // Copyright 2012-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... | {
let mut foo: Foo = Foo { bar: Bar(42) };
{ let foobar_immut = foo.get_immut(); }
{ let foobar_mut = foo.get_mut(); }
} | identifier_body | |
lib.rs | #[cfg(test)]
mod test;
use smallvec::{Array, SmallVec};
use std::convert::{From, Into};
use std::fmt::{self, Debug, Formatter};
use std::iter::FromIterator;
/// A `NibbleVec` backed by a `SmallVec` with 64 inline element slots.
/// This will not allocate until more than 64 elements are added.
pub type Nibblet = Nibb... | u8>) -> NibbleVec<A> {
NibbleVec::from_byte_vec(v)
}
}
impl<'a, A: Array<Item = u8>> From<&'a [u8]> for NibbleVec<A> {
#[inline]
fn from(v: &[u8]) -> NibbleVec<A> {
NibbleVec::from_byte_vec(v.into())
}
}
impl<A: Array<Item = u8>> Into<Vec<u8>> for NibbleVec<A> {
#[inline]
fn in... | Vec< | identifier_name |
lib.rs | #[cfg(test)]
mod test;
use smallvec::{Array, SmallVec};
use std::convert::{From, Into};
use std::fmt::{self, Debug, Formatter};
use std::iter::FromIterator;
/// A `NibbleVec` backed by a `SmallVec` with 64 inline element slots.
/// This will not allocate until more than 64 elements are added.
pub type Nibblet = Nibb... | pub fn into_bytes(self) -> Vec<u8> {
self.data.to_vec()
}
/// Get the number of elements stored in the vector.
#[inline]
pub fn len(&self) -> usize {
self.length
}
/// Returns `true` if the nibble vector has a length of 0.
#[inline]
pub fn is_empty(&self) -> bool {
... | #[inline] | random_line_split |
lib.rs | #[cfg(test)]
mod test;
use smallvec::{Array, SmallVec};
use std::convert::{From, Into};
use std::fmt::{self, Debug, Formatter};
use std::iter::FromIterator;
/// A `NibbleVec` backed by a `SmallVec` with 64 inline element slots.
/// This will not allocate until more than 64 elements are added.
pub type Nibblet = Nibb... | / Append another nibble vector whilst consuming this vector.
#[inline]
pub fn join(mut self, other: &NibbleVec<A>) -> NibbleVec<A> {
// If the length is even, we can append directly.
if self.length % 2 == 0 {
self.length += other.length;
self.data.extend_from_slice(&other... | // Copy up to the first half of the last byte.
for i in start..(end - 1) {
// The first half is the second half of the old entry.
let first_half = self.data[i] & 0x0f;
// The second half is the first half of the next entry.
let second_half = self.data[i + 1] >>... | identifier_body |
lib.rs | #[cfg(test)]
mod test;
use smallvec::{Array, SmallVec};
use std::convert::{From, Into};
use std::fmt::{self, Debug, Formatter};
use std::iter::FromIterator;
/// A `NibbleVec` backed by a `SmallVec` with 64 inline element slots.
/// This will not allocate until more than 64 elements are added.
pub type Nibblet = Nibb... |
}
/// Split function for odd *indices*.
#[inline]
fn split_odd(&mut self, idx: usize) -> NibbleVec<A> {
let mut tail = NibbleVec::new();
// Perform an overlap copy, copying the last nibble of the original vector only if
// the length of the new tail is *odd*.
let tail_... | {
self.split_odd(idx)
} | conditional_block |
shootout-binarytrees.rs | // xfail-test
// Broken due to arena API problems.
// 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/license... | (t: &tree) -> int {
match *t {
nil => { return 0; }
node(left, right, item) => {
return item + item_check(left) - item_check(right);
}
}
}
fn bottom_up_tree<'r>(arena: &'r mut arena::Arena, item: int, depth: int)
-> &'r tree<'r> {
if depth > 0 {
return a... | item_check | identifier_name |
shootout-binarytrees.rs | // xfail-test |
// 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... |
// Broken due to arena API problems. | random_line_split |
shootout-binarytrees.rs | // xfail-test
// Broken due to arena API problems.
// 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/license... | else if args.len() <= 1u {
~[~"", ~"8"]
} else {
args
};
let n = int::from_str(args[1]).get();
let min_depth = 4;
let mut max_depth;
if min_depth + 2 > n {
max_depth = min_depth + 2;
} else {
max_depth = n;
}
let mut stretch_arena = arena::Arena();
... | {
~[~"", ~"17"]
} | conditional_block |
shootout-binarytrees.rs | // xfail-test
// Broken due to arena API problems.
// 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/license... |
fn main() {
let args = os::args();
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"17"]
} else if args.len() <= 1u {
~[~"", ~"8"]
} else {
args
};
let n = int::from_str(args[1]).get();
let min_depth = 4;
let mut max_depth;
if min_depth + 2 > n ... | {
if depth > 0 {
return arena.alloc(
|| node(bottom_up_tree(arena, 2 * item - 1, depth - 1),
bottom_up_tree(arena, 2 * item, depth - 1),
item));
}
return arena.alloc(|| nil);
} | identifier_body |
issue-11577.rs | // pretty-expanded FIXME #23616
// 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 t... | { num: isize }
pub fn main() {
let vbar = Foo::VBar { num: 1 };
let Foo::VBar { num } = vbar;
assert_eq!(num, 1);
let sbar = SBar { num: 2 };
let SBar { num } = sbar;
assert_eq!(num, 2);
}
| SBar | identifier_name |
issue-11577.rs | // pretty-expanded FIXME #23616
// 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 t... |
struct SBar { num: isize }
pub fn main() {
let vbar = Foo::VBar { num: 1 };
let Foo::VBar { num } = vbar;
assert_eq!(num, 1);
let sbar = SBar { num: 2 };
let SBar { num } = sbar;
assert_eq!(num, 2);
} |
enum Foo {
VBar { num: isize }
} | random_line_split |
issue-11577.rs | // pretty-expanded FIXME #23616
// 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 t... | {
let vbar = Foo::VBar { num: 1 };
let Foo::VBar { num } = vbar;
assert_eq!(num, 1);
let sbar = SBar { num: 2 };
let SBar { num } = sbar;
assert_eq!(num, 2);
} | identifier_body | |
client.rs | use std::fmt;
use std::sync::Mutex;
use std::cell::{RefCell, UnsafeCell};
use std::ptr;
use wrust_io::mio;
use wrust_io::mio::tcp::*;
use wrust_io::mio::unix::*;
use wrust_types::Result;
use wrust_types::net::Protocol;
use wrust_types::net::connection::{State, Descriptor};
use wrust_module::stream::{Intention, Flush};
... | (&self, data: Option<LeftData>) {
let cell = self.left_data.lock().unwrap();
let mut left_data = data;
unsafe { ptr::swap(&mut left_data, cell.get()); }
}
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Client #{:?}", self.token)
}
}
| set_left_data | identifier_name |
client.rs | use std::fmt;
use std::sync::Mutex;
use std::cell::{RefCell, UnsafeCell};
use std::ptr;
use wrust_io::mio;
use wrust_io::mio::tcp::*;
use wrust_io::mio::unix::*;
use wrust_types::Result;
use wrust_types::net::Protocol;
use wrust_types::net::connection::{State, Descriptor};
use wrust_module::stream::{Intention, Flush};
... |
pub fn intention(&self) -> &Intention {
&self.intention
}
pub fn flush(&self) -> &Flush {
&self.flush
}
pub fn consume(self) -> (Vec<u8>, (Intention, Flush)) {
(self.data, (self.intention, self.flush))
}
}
pub struct Client {
server_token: mio::Token,
token: mio::Token,
socket: Mutex<RefCell<Client... | {
&self.data
} | identifier_body |
client.rs | use std::fmt;
use std::sync::Mutex;
use std::cell::{RefCell, UnsafeCell};
use std::ptr;
use wrust_io::mio;
use wrust_io::mio::tcp::*;
use wrust_io::mio::unix::*;
use wrust_types::Result;
use wrust_types::net::Protocol;
use wrust_types::net::connection::{State, Descriptor};
use wrust_module::stream::{Intention, Flush};
... |
pub fn then_on_socket<F, T>(&self, mut func: F) -> Result<T>
where F: FnMut(&mut ClientProtocol) -> Result<T> {
let guard = self.socket.lock().unwrap();
let mut cell = guard.borrow_mut();
func(&mut *cell)
}
pub fn left_data(&self) -> Option<LeftData> {
let cell = self.left_data.lock().unwrap();
let mut... | &self.descriptor
} | random_line_split |
mod.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/. */
//! Tests for parsing and serialization of values/properties
use cssparser::Parser;
use media_queries::CSSErrorRe... |
// This is a macro so that the file/line information
// is preserved in the panic
macro_rules! assert_roundtrip_with_context {
($fun:expr, $string:expr) => {
assert_roundtrip_with_context!($fun, $string, $string);
};
($fun:expr,$input:expr, $output:expr) => {
let url = ::servo_url::ServoUr... | {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest));
let mut parser = Parser::new(s);
f(&context, &mut parser)
} | identifier_body |
mod.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/. */
//! Tests for parsing and serialization of values/properties
use cssparser::Parser;
use media_queries::CSSErrorRe... | <T, F: Fn(&ParserContext, &mut Parser) -> Result<T, ()>>(f: F, s: &str) -> Result<T, ()> {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest));
let mut parser = Parser::new(s);
f(&context, &mut parser... | parse | identifier_name |
mod.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/. */
//! Tests for parsing and serialization of values/properties
use cssparser::Parser;
use media_queries::CSSErrorRe... | mod image;
mod inherited_box;
mod inherited_text;
mod mask;
mod position;
mod selectors; | mod font; | random_line_split |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block.
#[derive(Debug)]
pub struct UniformBuffer<T> where T: Copy {
buffer: B... | (&self) -> &BufferView<T> {
&self.buffer
}
}
impl<T> DerefMut for UniformBuffer<T> where T: Copy {
fn deref_mut(&mut self) -> &mut BufferView<T> {
&mut self.buffer
}
}
impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Copy {
fn as_uniform_value(&self) -> Unifo... | deref | identifier_name |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block.
#[derive(Debug)]
pub struct UniformBuffer<T> where T: Copy {
buffer: B... | };
Some(UniformBuffer {
buffer: buffer,
})
}
/// Creates an empty buffer.
///
/// # Features
///
/// Only available if the `gl_uniform_blocks` feature is enabled.
#[cfg(feature = "gl_uniform_blocks")]
pub fn empty<F>(facade: &F) -> UniformBuffer<T> w... | pub fn new_if_supported<F>(facade: &F, data: T) -> Option<UniformBuffer<T>> where F: Facade {
let buffer = match BufferView::new(facade, &data, BufferType::UniformBuffer, true) {
Ok(b) => b,
Err(BufferCreationError::BufferTypeNotSupported) => return None,
e @ Err(_) => e.... | random_line_split |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block.
#[derive(Debug)]
pub struct UniformBuffer<T> where T: Copy {
buffer: B... |
/// Creates an empty buffer.
///
/// # Features
///
/// Only available if the `gl_uniform_blocks` feature is enabled.
#[cfg(feature = "gl_uniform_blocks")]
pub fn empty<F>(facade: &F) -> UniformBuffer<T> where F: Facade {
UniformBuffer::empty_if_supported(facade).unwrap()
}
... | {
let buffer = match BufferView::new(facade, &data, BufferType::UniformBuffer, true) {
Ok(b) => b,
Err(BufferCreationError::BufferTypeNotSupported) => return None,
e @ Err(_) => e.unwrap(),
};
Some(UniformBuffer {
buffer: buffer,
})
} | identifier_body |
rotate_point.rs | // Copyright 2016 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | {
let cylinders = Cylinders::new();
let rotate_point = RotatePoint::new(cylinders).set_x_angle(60.0);
debug::render_noise_module3("rotate_point.png", &rotate_point, 1024, 1024, 50);
} | identifier_body | |
rotate_point.rs | // Copyright 2016 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | let cylinders = Cylinders::new();
let rotate_point = RotatePoint::new(cylinders).set_x_angle(60.0);
debug::render_noise_module3("rotate_point.png", &rotate_point, 1024, 1024, 50);
} | random_line_split | |
rotate_point.rs | // Copyright 2016 The Noise-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | () {
let cylinders = Cylinders::new();
let rotate_point = RotatePoint::new(cylinders).set_x_angle(60.0);
debug::render_noise_module3("rotate_point.png", &rotate_point, 1024, 1024, 50);
}
| main | identifier_name |
shared_lock.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/. */
//! Different objects protected by the same lock
#[cfg(feature = "gecko")]
use atomic_refcell::{AtomicRefCell, At... |
/// Obtain the lock for writing (servo).
#[cfg(feature = "servo")]
pub fn write(&self) -> SharedRwLockWriteGuard {
self.arc.raw_write();
SharedRwLockWriteGuard(self)
}
/// Obtain the lock for writing (gecko).
#[cfg(feature = "gecko")]
pub fn write(&self) -> SharedRwLockWri... | {
SharedRwLockReadGuard(self.cell.borrow())
} | identifier_body |
shared_lock.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/. */
//! Different objects protected by the same lock
#[cfg(feature = "gecko")]
use atomic_refcell::{AtomicRefCell, At... | () -> Self {
SharedRwLock {
arc: Arc::new(RwLock::new(()))
}
}
/// Create a new shared lock (gecko).
#[cfg(feature = "gecko")]
pub fn new() -> Self {
SharedRwLock {
cell: Arc::new(AtomicRefCell::new(SomethingZeroSizedButTyped))
}
}
/// Wr... | new | identifier_name |
shared_lock.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/. */
//! Different objects protected by the same lock
#[cfg(feature = "gecko")]
use atomic_refcell::{AtomicRefCell, At... | self.arc.raw_read();
SharedRwLockReadGuard(self)
}
/// Obtain the lock for reading (gecko).
#[cfg(feature = "gecko")]
pub fn read(&self) -> SharedRwLockReadGuard {
SharedRwLockReadGuard(self.cell.borrow())
}
/// Obtain the lock for writing (servo).
#[cfg(feature = "... | #[cfg(feature = "servo")]
pub fn read(&self) -> SharedRwLockReadGuard { | random_line_split |
redirect.rs | use response::{Response, Responder};
use http::hyper::header;
use http::Status;
/// An empty redirect response to a given URL.
///
/// This type simplifies returning a redirect response to the client.
#[derive(Debug)]
pub struct Redirect(Status, String);
impl Redirect {
/// Construct a temporary "see other" (303)... | /// Construct a permanent "moved" (301) redirect response. This response
/// should only be used for permanent redirects as it can be cached by
/// browsers. Because different clients may respond differently to this type
/// of redirect, a `308` redirect, which disambiguates, is preferred.
///
/... | random_line_split | |
redirect.rs | use response::{Response, Responder};
use http::hyper::header;
use http::Status;
/// An empty redirect response to a given URL.
///
/// This type simplifies returning a redirect response to the client.
#[derive(Debug)]
pub struct Redirect(Status, String);
impl Redirect {
/// Construct a temporary "see other" (303)... | (uri: &str) -> Redirect {
Redirect(Status::SeeOther, String::from(uri))
}
/// Construct a "temporary" (307) redirect response. This response instructs
/// the client to reissue the current request to a different URL,
/// maintaining the contents of the request identically. This means that,
... | to | identifier_name |
main.rs | /*
*Red, a line editor derived from ed editor
*Copyright (C) 2017 Walter Bruschi
*
*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 ... |
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
// optional option that does not take an argument
opts.optflag("h", "help", "print this help menu");
// optional option that takes an argument
opts.optopt("p", "prompt"... | {
let brief = format!("Usage: {} FILE", program);
print!("{}", opts.usage(&brief));
} | identifier_body |
main.rs | /*
*Red, a line editor derived from ed editor
*Copyright (C) 2017 Walter Bruschi
*
*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 ... | ,
Err(e) => {
println!("{}", e.to_string());
return;
}
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let prompt = matches.opt_str("p").unwrap_or("*".to_string());
let filename = if!matches.free.is_empty() {
... | { m } | conditional_block |
main.rs | /*
*Red, a line editor derived from ed editor
*Copyright (C) 2017 Walter Bruschi
*
*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 ... | () {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
// optional option that does not take an argument
opts.optflag("h", "help", "print this help menu");
// optional option that takes an argument
opts.optopt("p", "prompt", "use ST... | main | identifier_name |
main.rs | /*
*Red, a line editor derived from ed editor
*Copyright (C) 2017 Walter Bruschi
*
*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 ... | *This program is derived from Free Software Foundation version of ed.
*This program has been modified to be written in Rust insead of C.
*Any credit to the original work is theirs.
*Copyright (C) 1993, 1994, 2006-2017 Free Software Foundation, Inc.
*The original work can be found at the following website:
*https:... | *You should have received a copy of the GNU General Public License
*along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*CREDITS | random_line_split |
computations.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
use energy::{Potential, PairPotential};
/// Alternative energy and forces computation.
///
/// The `Computation` trait represent an alternative way to compute a given
/// potential. For example using inte... | self, r: f64) -> f64 {
debug_assert_eq!(self.energy_table.len(), self.force_table.len());
let bin = f64::floor(r / self.delta) as usize;
if bin < self.energy_table.len() - 1 {
let dx = r - (bin as f64) * self.delta;
let slope = (self.energy_table[bin + 1] - self.energy_ta... | mpute_energy(& | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.