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 | //! # Getting started
//!
//! ```rust,no_run
//! extern crate sdl2;
//!
//! use sdl2::pixels::Color;
//! use sdl2::event::Event;
//! use sdl2::keyboard::Keycode;
//! use std::time::Duration;
//!
//! pub fn main() {
//! let sdl_context = sdl2::init().unwrap();
//! let video_subsystem = sdl_context.video().unwrap... | pub use crate::sdl::*;
pub mod clipboard;
pub mod cpuinfo;
#[macro_use]
mod macros;
pub mod audio;
pub mod controller;
pub mod event;
pub mod filesystem;
pub mod haptic;
pub mod hint;
pub mod joystick;
pub mod keyboard;
pub mod log;
pub mod messagebox;
pub mod mouse;
pub mod pixels;
pub mod rect;
pub mod render;
pub m... |
#[cfg(feature = "gfx")]
extern crate c_vec;
| random_line_split |
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip... | impl FileSystem for InMemoryFileSystem {
type File = InMemoryFile;
fn open_file<P>(&self, path: P) -> io::Result<Self::File>
where P: AsRef<Path> + Send +'static {
let file_path = path.as_ref().to_path_buf();
self.run_with_lock(|files| {
if!files.contains_key(&file_path) {... | random_line_split | |
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip... | () -> InMemoryFileSystem {
InMemoryFileSystem{ files: Arc::new(Mutex::new(HashMap::new())) }
}
pub fn run_with_lock<C, R>(&self, call: C) -> R
where C: FnOnce(&mut HashMap<PathBuf, Vec<u8>>) -> R {
let mut lock_files = self.files.lock().unwrap();
call(&mut *lock_files)
}
}
... | new | identifier_name |
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip... |
}
struct InMemoryFile {
path: PathBuf
}
impl FileSystem for InMemoryFileSystem {
type File = InMemoryFile;
fn open_file<P>(&self, path: P) -> io::Result<Self::File>
where P: AsRef<Path> + Send +'static {
let file_path = path.as_ref().to_path_buf();
self.run_with_lock(|files| {
... | {
let mut lock_files = self.files.lock().unwrap();
call(&mut *lock_files)
} | identifier_body |
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip... |
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
if bytes_to_copy!= 0 {
file_buffer[cast_offset..(cast_offset + bytes_to_copy)].clone_from_slice(buffer);
}
// TODO:... | {
file_buffer.resize(last_byte_pos, 0);
} | conditional_block |
harmonic.rs | //! Provides functions for calculating
//! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number)
//! numbers
use crate::consts;
use crate::function::gamma;
/// Computes the `t`-th harmonic number
///
/// # Remarks
///
/// Returns `1` as a special case when `t == 0`
pub fn harmonic(t: u64) -> f64 {
match t {
... | assert_almost_eq!(super::gen_harmonic(4, 1.0), 2.083333333333333333333, 1e-14);
assert_eq!(super::gen_harmonic(4, 3.0), 1.177662037037037037037);
assert_eq!(super::gen_harmonic(4, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(4, f64::NEG_INFINITY), f64::INFINITY);
}
} | assert_eq!(super::gen_harmonic(1, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, 1.0), 1.5);
assert_eq!(super::gen_harmonic(2, 3.0), 1.125);
assert_eq!(super::gen_harmonic(2, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, f64::NEG_INFINITY), f64::INFINITY); | random_line_split |
harmonic.rs | //! Provides functions for calculating
//! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number)
//! numbers
use crate::consts;
use crate::function::gamma;
/// Computes the `t`-th harmonic number
///
/// # Remarks
///
/// Returns `1` as a special case when `t == 0`
pub fn harmonic(t: u64) -> f64 {
match t {
... | () {
assert_eq!(super::gen_harmonic(0, 0.0), 1.0);
assert_eq!(super::gen_harmonic(0, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(0, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(1, 0.0), 1.0);
assert_eq!(super::gen_harmonic(1, f64::INFINITY), 1.0);
ass... | test_gen_harmonic | identifier_name |
harmonic.rs | //! Provides functions for calculating
//! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number)
//! numbers
use crate::consts;
use crate::function::gamma;
/// Computes the `t`-th harmonic number
///
/// # Remarks
///
/// Returns `1` as a special case when `t == 0`
pub fn harmonic(t: u64) -> f64 {
match t {
... |
#[test]
fn test_gen_harmonic() {
assert_eq!(super::gen_harmonic(0, 0.0), 1.0);
assert_eq!(super::gen_harmonic(0, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(0, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(1, 0.0), 1.0);
assert_eq!(super::gen_harmoni... | {
assert_eq!(super::harmonic(0), 1.0);
assert_almost_eq!(super::harmonic(1), 1.0, 1e-14);
assert_almost_eq!(super::harmonic(2), 1.5, 1e-14);
assert_almost_eq!(super::harmonic(4), 2.083333333333333333333, 1e-14);
assert_almost_eq!(super::harmonic(8), 2.717857142857142857143, 1e-14... | identifier_body |
epoll.rs | use {Errno, Result};
use libc::{self, c_int};
use std::os::unix::io::RawFd;
use std::ptr;
use std::mem;
use ::Error;
libc_bitflags!(
pub flags EpollFlags: libc::c_int {
EPOLLIN,
EPOLLPRI,
EPOLLOUT,
EPOLLRDNORM,
EPOLLRDBAND,
EPOLLWRNORM,
EPOLLWRBAND,
E... | {
event: libc::epoll_event,
}
impl EpollEvent {
pub fn new(events: EpollFlags, data: u64) -> Self {
EpollEvent { event: libc::epoll_event { events: events.bits() as u32, u64: data } }
}
pub fn empty() -> Self {
unsafe { mem::zeroed::<EpollEvent>() }
}
pub fn events(&self) -> ... | EpollEvent | identifier_name |
epoll.rs | use {Errno, Result};
use libc::{self, c_int};
use std::os::unix::io::RawFd;
use std::ptr;
use std::mem;
use ::Error;
libc_bitflags!(
pub flags EpollFlags: libc::c_int {
EPOLLIN,
EPOLLPRI,
EPOLLOUT,
EPOLLRDNORM,
EPOLLRDBAND,
EPOLLWRNORM,
EPOLLWRBAND,
E... |
}
impl<'a> Into<&'a mut EpollEvent> for Option<&'a mut EpollEvent> {
#[inline]
fn into(self) -> &'a mut EpollEvent {
match self {
Some(epoll_event) => epoll_event,
None => unsafe { &mut *ptr::null_mut::<EpollEvent>() }
}
}
}
#[inline]
pub fn epoll_create() -> Resul... | {
self.event.u64
} | identifier_body |
epoll.rs | use {Errno, Result};
use libc::{self, c_int};
use std::os::unix::io::RawFd;
use std::ptr;
use std::mem;
use ::Error;
libc_bitflags!(
pub flags EpollFlags: libc::c_int {
EPOLLIN,
EPOLLPRI,
EPOLLOUT,
EPOLLRDNORM,
EPOLLRDBAND,
EPOLLWRNORM,
EPOLLWRBAND,
E... | } else {
let res = unsafe { libc::epoll_ctl(epfd, op as c_int, fd, &mut event.event) };
Errno::result(res).map(drop)
}
}
#[inline]
pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> {
let res = unsafe {
libc::epoll_wait(epfd, events.as_mut_... | {
let event: &mut EpollEvent = event.into();
if event as *const EpollEvent == ptr::null() && op != EpollOp::EpollCtlDel {
Err(Error::Sys(Errno::EINVAL)) | random_line_split |
marching_triangles_performance.rs | extern crate isosurface;
extern crate ndarray;
use ndarray::Array;
use isosurface::marching_triangles;
fn | () {
let n = 256;
let xs = Array::linspace(-0.5f64, 0.5, n);
let ys = Array::linspace(-0.5, 0.5, n);
let dim = (xs.len(), ys.len());
let u = {
let mut u = Array::from_elem(dim, 0.);
for ((i, j), u) in u.indexed_iter_mut() {
let (x, y) = (xs[i], ys[j]);
*u =... | main | identifier_name |
marching_triangles_performance.rs | extern crate isosurface;
extern crate ndarray;
use ndarray::Array;
use isosurface::marching_triangles;
fn main() | m += verts.len();
}
println!("total vert num = {}", m);
}
| {
let n = 256;
let xs = Array::linspace(-0.5f64, 0.5, n);
let ys = Array::linspace(-0.5, 0.5, n);
let dim = (xs.len(), ys.len());
let u = {
let mut u = Array::from_elem(dim, 0.);
for ((i, j), u) in u.indexed_iter_mut() {
let (x, y) = (xs[i], ys[j]);
*u = (x... | identifier_body |
marching_triangles_performance.rs | extern crate isosurface;
extern crate ndarray;
use ndarray::Array;
use isosurface::marching_triangles;
fn main() {
let n = 256;
let xs = Array::linspace(-0.5f64, 0.5, n);
let ys = Array::linspace(-0.5, 0.5, n); | let u = {
let mut u = Array::from_elem(dim, 0.);
for ((i, j), u) in u.indexed_iter_mut() {
let (x, y) = (xs[i], ys[j]);
*u = (x * x + y * y).sqrt() - 0.4;
}
u
};
let mut m = 0;
for _ in 0..1000 {
let verts = marching_triangles(u.as_slice(... |
let dim = (xs.len(), ys.len());
| random_line_split |
generic-lifetime-trait-impl.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 |
generic-lifetime-trait-impl.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 ... | //~ ERROR lifetime
}
fn main() {
}
| { fail!() } | identifier_body |
generic-lifetime-trait-impl.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 | // except according to those terms.
// This code used to produce an ICE on the definition of trait Bar
// with the following message:
//
// Type parameter out of range when substituting in region 'a (root
// type=fn(Self) -> 'astr) (space=FnSpace, index=0)
//
// Regression test for issue #16218.
trait Bar<'a> {}
tra... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
urlsearchparams.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams... | ,
Some(USVStringOrURLSearchParams::URLSearchParams(init)) => {
// Step 3.
*query.list.borrow_mut() = init.list.borrow().clone();
},
None => {}
}
// Step 4.
Ok(query)
}
pub fn set_list(&self, list: Vec<(String, String)>)... | {
// Step 2.
*query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes())
.into_owned().collect();
} | conditional_block |
urlsearchparams.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams... | (&self, name: USVString, value: USVString) {
{
// Step 1.
let mut list = self.list.borrow_mut();
let mut index = None;
let mut i = 0;
list.retain(|&(ref k, _)| {
if index.is_none() {
if k == &name.0 {
... | Set | identifier_name |
urlsearchparams.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams... | USVString(value)
}
fn get_key_at_index(&self, n: u32) -> USVString {
let key = self.list.borrow()[n as usize].0.clone();
USVString(key)
}
} |
fn get_value_at_index(&self, n: u32) -> USVString {
let value = self.list.borrow()[n as usize].1.clone(); | random_line_split |
urlsearchparams.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParams... |
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
fn update_steps(&self) {
if let Some(url) = self.url.root() {
url.set_query_pairs(&self.list.borrow())
}
}
}
impl Iterable for URLSearchParams {
type Key = USVString;
type Value =... | {
let list = self.list.borrow();
form_urlencoded::Serializer::new(String::new())
.encoding_override(encoding)
.extend_pairs(&*list)
.finish()
} | identifier_body |
result.rs | [I/O](../../std/io/index.html).
//!
//! A simple function returning `Result` might be
//! defined and used like so:
//!
//! ~~~
//! #[deriving(Show)]
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
//! if header.len() < 1 {
//! return Err("... | //! Err(e) => return Err(e)
//! }
//! return file.write_line(format!("rating: {}", info.rating).as_slice());
//! }
//! ~~~
//!
//! With this:
//!
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
//! name: String,
//! age: int,
//! rating: int
//! }
//!
//! fn writ... | //! Err(e) => return Err(e)
//! }
//! match file.write_line(format!("age: {}", info.age).as_slice()) {
//! Ok(_) => (), | random_line_split |
result.rs | /O](../../std/io/index.html).
//!
//! A simple function returning `Result` might be
//! defined and used like so:
//!
//! ~~~
//! #[deriving(Show)]
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
//! if header.len() < 1 {
//! return Err("inv... |
/// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
///
/// This function can be used for control flow based on result values
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
match ... | {
match self {
Ok(_) => res,
Err(e) => Err(e),
}
} | identifier_body |
result.rs | /O](../../std/io/index.html).
//!
//! A simple function returning `Result` might be
//! defined and used like so:
//!
//! ~~~
//! #[deriving(Show)]
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
//! if header.len() < 1 {
//! return Err("inv... | (self) -> Item<T> {
Item{opt: self.ok()}
}
////////////////////////////////////////////////////////////////////////
// Boolean operations on the values, eager and lazy
/////////////////////////////////////////////////////////////////////////
/// Returns `res` if the result is `Ok`, otherwi... | move_iter | identifier_name |
cpp_box.rs | use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection};
use crate::vector_ops::{Data, DataMut, Size};
use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast};
use std::ops::Deref;
use std::{fmt, mem, ptr, slice};
/// Objects that can be deleted using C++'s `delete` opera... | () {
let value1 = Rc::new(RefCell::new(10));
let object1 = Struct1 {
value: value1.clone(),
};
assert!(*value1.borrow() == 10);
unsafe {
CppBox::new(Ptr::from_raw(&object1));
}
assert!(*value1.borrow() == 42);
}
}
| test_drop_calls_deleter | identifier_name |
cpp_box.rs | use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection};
use crate::vector_ops::{Data, DataMut, Size};
use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast};
use std::ops::Deref;
use std::{fmt, mem, ptr, slice};
/// Objects that can be deleted using C++'s `delete` opera... | /// ensure that the object will be deleted at some point.
pub fn into_raw_ptr(self) -> *mut T {
let ptr = self.0.as_ptr();
mem::forget(self);
ptr
}
/// Destroys the box without deleting the object and returns a pointer to the content.
/// The caller of the function becomes t... | /// Destroys the box without deleting the object and returns a raw pointer to the content.
/// The caller of the function becomes the owner of the object and should | random_line_split |
cpp_box.rs | use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection};
use crate::vector_ops::{Data, DataMut, Size};
use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast};
use std::ops::Deref;
use std::{fmt, mem, ptr, slice};
/// Objects that can be deleted using C++'s `delete` opera... |
/// Returns a reference to the value.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> &'a T {
&*self.0.a... | {
Ref::from_raw_non_null(self.0)
} | identifier_body |
opt_vec.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 ... |
impl<T:Copy> OptVec<T> {
fn prepend(&self, t: T) -> OptVec<T> {
let mut v0 = ~[t];
match *self {
Empty => {}
Vec(ref v1) => { v0.push_all(*v1); }
}
return Vec(v0);
}
fn push_all<I: BaseIter<T>>(&mut self, from: &I) {
for from.each |e| {
... | {
match v {
Empty => ~[],
Vec(v) => v
}
} | identifier_body |
opt_vec.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 ... | Vec(v) => v
}
}
impl<T:Copy> OptVec<T> {
fn prepend(&self, t: T) -> OptVec<T> {
let mut v0 = ~[t];
match *self {
Empty => {}
Vec(ref v1) => { v0.push_all(*v1); }
}
return Vec(v0);
}
fn push_all<I: BaseIter<T>>(&mut self, from: &I) {
... | random_line_split | |
opt_vec.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 ... | <'a>(&'a self, i: uint) -> &'a T {
match *self {
Empty => fail!("Invalid index %u", i),
Vec(ref v) => &v[i]
}
}
fn is_empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> uint {
match *self {
Empty => 0,
Vec(ref v) =>... | get | identifier_name |
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use pl... | (&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) ... | fmt | identifier_name |
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use pl... |
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTOD... | {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
} | identifier_body |
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use pl... | #[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
if self.stretch!= other.stretch || self.italic!= other.italic {
// A value higher than all weights.
return 1000
}
((self.weight as i16) - (other.weight as i16)).abs() as u32
}
}
impl P... | /// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)). | random_line_split |
x86_64_unknown_dragonfly.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 ... | () -> Target {
let mut base = super::dragonfly_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
... | target | identifier_name |
x86_64_unknown_dragonfly.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 ... | } | random_line_split | |
x86_64_unknown_dragonfly.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 ... | {
let mut base = super::dragonfly_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
... | identifier_body | |
parallel.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/. */
//! Implements parallel traversal over the DOM tree.
//!
//! This traversal is based on Rayon, and therefore its s... | if may_dispatch_tail {
top_down_dom(&work, root, traversal_data, scope, pool, traversal, tls);
} else {
scope.spawn(move |scope| {
let work = work;
top_down_dom(&work, root, traversal_data, scope, pool, traversal, tls);
});
}
... | random_line_split | |
parallel.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/. */
//! Implements parallel traversal over the DOM tree.
//!
//! This traversal is based on Rayon, and therefore its s... | <E, D>(traversal: &D,
root: E,
token: PreTraverseToken,
pool: &rayon::ThreadPool)
where E: TElement,
D: DomTraversal<E>,
{
let dump_stats = traversal.shared_context().options.dump_style_statistics;
let start_time = if du... | traverse_dom | identifier_name |
keypad.rs | use sdl::event::Key;
pub struct Keypad {
keys: [bool; 16],
}
impl Keypad {
pub fn new() -> Keypad {
Keypad { keys: [false; 16] }
}
pub fn pressed(&mut self, index: usize) -> bool {
self.keys[index]
}
pub fn press(&mut self, key: Key, state: bool) {
match key {
... | Key::A => self.set_key(0x7, state),
Key::S => self.set_key(0x8, state),
Key::D => self.set_key(0x9, state),
Key::F => self.set_key(0xe, state),
Key::Z => self.set_key(0xa, state),
Key::X => self.set_key(0x0, state),
Key::C => self.set_k... | Key::R => self.set_key(0xd, state), | random_line_split |
keypad.rs | use sdl::event::Key;
pub struct Keypad {
keys: [bool; 16],
}
impl Keypad {
pub fn new() -> Keypad {
Keypad { keys: [false; 16] }
}
pub fn pressed(&mut self, index: usize) -> bool {
self.keys[index]
}
pub fn press(&mut self, key: Key, state: bool) | }
fn set_key(&mut self, index: usize, state: bool) {
self.keys[index] = state;
}
}
| {
match key {
Key::Num1 => self.set_key(0x1, state),
Key::Num2 => self.set_key(0x2, state),
Key::Num3 => self.set_key(0x3, state),
Key::Num4 => self.set_key(0xc, state),
Key::Q => self.set_key(0x4, state),
Key::W => self.set_key(0x5, state)... | identifier_body |
keypad.rs | use sdl::event::Key;
pub struct Keypad {
keys: [bool; 16],
}
impl Keypad {
pub fn | () -> Keypad {
Keypad { keys: [false; 16] }
}
pub fn pressed(&mut self, index: usize) -> bool {
self.keys[index]
}
pub fn press(&mut self, key: Key, state: bool) {
match key {
Key::Num1 => self.set_key(0x1, state),
Key::Num2 => self.set_key(0x2, state),
... | new | identifier_name |
allocate.rs | // Our use cases
use super::expander;
pub fn allocate_expander(par_eax: i32, par_edx: i32) -> expander::SoundExpander {
let mut sound_expander = expander::SoundExpander::new();
let mut par_eax = par_eax;
let mut par_edx = par_edx;
sound_expander.wave_format_ex.format_tag = expander::WAVE_FORMAT_PCM as... | sound_expander.memb_5C = 1;
sound_expander.memb_4C = 0x7FFF;
sound_expander.memb_54 = 0;
sound_expander.previous = Box::new(expander::SoundExpander::new());
sound_expander.next = Box::new(expander::SoundExpander::new());
sound_expander
}
pub fn allocate_sound(par_ecx: i32, par_ebx: i32) -> ex... | random_line_split | |
allocate.rs | // Our use cases
use super::expander;
pub fn | (par_eax: i32, par_edx: i32) -> expander::SoundExpander {
let mut sound_expander = expander::SoundExpander::new();
let mut par_eax = par_eax;
let mut par_edx = par_edx;
sound_expander.wave_format_ex.format_tag = expander::WAVE_FORMAT_PCM as u16;
sound_expander.wave_format_ex.channels = 1;
if 8... | allocate_expander | identifier_name |
allocate.rs | // Our use cases
use super::expander;
pub fn allocate_expander(par_eax: i32, par_edx: i32) -> expander::SoundExpander {
let mut sound_expander = expander::SoundExpander::new();
let mut par_eax = par_eax;
let mut par_edx = par_edx;
sound_expander.wave_format_ex.format_tag = expander::WAVE_FORMAT_PCM as... | {
let mut edx = 0x0A;
let mut eax = 0;
match par_ebx {
0x0D => eax = 1,
0x0E => eax = 2,
_ => eax = 0,
}
match par_ecx {
0x0F => eax = eax | 4,
_ => edx = edx | 0x20,
}
allocate_expander(eax, edx)
} | identifier_body | |
de.rs | use serde::{Deserialize, Deserializer};
use serde_derive::Deserialize;
use tera::{Map, Value};
/// Used as an attribute when we want to convert from TOML to a string date
/// If a TOML datetime isn't present, it will accept a string and push it through
/// TOML's date time parser to ensure only valid dates are accepte... | {
Datetime(toml::value::Datetime),
String(String),
}
match MaybeDatetime::deserialize(deserializer)? {
MaybeDatetime::Datetime(d) => Ok(Some(d.to_string())),
MaybeDatetime::String(s) => match toml::value::Datetime::from_str(&s) {
Ok(d) => Ok(Some(d.to_string())),
... | MaybeDatetime | identifier_name |
de.rs | use serde::{Deserialize, Deserializer};
use serde_derive::Deserialize;
use tera::{Map, Value};
/// Used as an attribute when we want to convert from TOML to a string date
/// If a TOML datetime isn't present, it will accept a string and push it through
/// TOML's date time parser to ensure only valid dates are accepte... | new.insert(key, Value::Array(new_arr));
}
_ => {
new.insert(key, value);
}
}
}
Value::Object(new)
} | random_line_split | |
errhandlingapi.rs | // Copyright © 2015-2017 winapi-rs developers
// 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.
// All files in the project carrying such notice may not be copied,... | ) -> LONG;
pub fn SetUnhandledExceptionFilter(
lpTopLevelExceptionFilter: LPTOP_LEVEL_EXCEPTION_FILTER,
) -> LPTOP_LEVEL_EXCEPTION_FILTER;
pub fn GetLastError() -> DWORD;
pub fn SetLastError(
dwErrCode: DWORD,
);
pub fn GetErrorMode() -> UINT;
pub fn SetErrorMode(
... | nNumberOfArguments: DWORD,
lpArguments: *const ULONG_PTR,
);
pub fn UnhandledExceptionFilter(
ExceptionInfo: *mut EXCEPTION_POINTERS, | random_line_split |
atmega328p.rs | use chips;
use io;
pub struct Chip;
impl chips::Chip for Chip
{
fn flash_size() -> usize {
32 * 1024 // 32 KB
}
fn memory_size() -> usize {
2 * 1024 // 2KB
}
fn io_ports() -> Vec<io::Port> |
}
| {
vec![
io::Port::new(0x03), // PINB
io::Port::new(0x04), // DDRB
io::Port::new(0x05), // PORTB
io::Port::new(0x06), // PINC
io::Port::new(0x07), // DDRC
io::Port::new(0x08), // PORTC
io::Port::new(0x09), // PIND
i... | identifier_body |
atmega328p.rs | use chips;
use io;
pub struct Chip;
impl chips::Chip for Chip
{
fn flash_size() -> usize {
32 * 1024 // 32 KB
}
fn | () -> usize {
2 * 1024 // 2KB
}
fn io_ports() -> Vec<io::Port> {
vec![
io::Port::new(0x03), // PINB
io::Port::new(0x04), // DDRB
io::Port::new(0x05), // PORTB
io::Port::new(0x06), // PINC
io::Port::new(0x07), // DDRC
io::P... | memory_size | identifier_name |
atmega328p.rs | use chips;
use io;
pub struct Chip;
| {
fn flash_size() -> usize {
32 * 1024 // 32 KB
}
fn memory_size() -> usize {
2 * 1024 // 2KB
}
fn io_ports() -> Vec<io::Port> {
vec![
io::Port::new(0x03), // PINB
io::Port::new(0x04), // DDRB
io::Port::new(0x05), // PORTB
io... | impl chips::Chip for Chip | random_line_split |
context.rs | use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use num::BigRational;
use lang::Filter;
#[derive(Clone, Debug)]
pub enum PrecedenceGroup {
AndThen,
Circumfix
}
#[derive(Clone)]
pub struct Context {
/// A function called each time the parser constructs a new filter anywhere in the synta... | (&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Context {{ filter_allowed: [Fn(&Filter) -> bool], operators: {:?} }}", self.operators)
}
}
| fmt | identifier_name |
context.rs | use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use num::BigRational;
use lang::Filter;
#[derive(Clone, Debug)]
pub enum PrecedenceGroup {
AndThen,
Circumfix
}
#[derive(Clone)]
pub struct Context {
/// A function called each time the parser constructs a new filter anywhere in the synta... | } |
impl fmt::Debug for Context {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Context {{ filter_allowed: [Fn(&Filter) -> bool], operators: {:?} }}", self.operators)
} | random_line_split |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{Stea... | while let Ok(envelope) = test_rx.try_recv() {
assert_matches!(envelope.msg, Msg::ClusterStatus(_));
}
break;
}
}
}
} | let notifications = poller.wait(10).unwrap();
if notifications.len() != 0 {
// We have registered, otherwise we wouldn't have gotten a response
// Let's drain the receiver, because we may have returned from a previous poll
// before the previous Cl... | random_line_split |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{Stea... |
#[allow(dead_code)] // Not used in all tests
pub fn start_nodes(n: usize) -> (Vec<Node<RabbleUserMsg>>, Vec<JoinHandle<()>>) {
let term = slog_term::streamer().build();
let drain = slog_envlogger::LogBuilder::new(term)
.filter(None, slog::FilterLevel::Debug).build();
let root_logger = slog::Logger:... | {
(1..n + 1).map(|n| {
NodeId {
name: format!("node{}", n),
addr: format!("127.0.0.1:1100{}", n)
}
}).collect()
} | identifier_body |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{Stea... | <F>(timeout: Duration, mut f: F) -> bool
where F: FnMut() -> bool
{
let sleep_time = Duration::milliseconds(10);
let start = SteadyTime::now();
while let false = f() {
thread::sleep(sleep_time.to_std().unwrap());
if SteadyTime::now() - start > timeout {
return false;
... | wait_for | identifier_name |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{Stea... |
// Just busy wait instead of using a poller in this test.
assert_eq!(true, wait_for(Duration::seconds(5), || {
// We don't know if it's writable, but we want to actually try the write
serializer.set_writable();
match serializer.write_msgs(sock, None) {
Ok(true) => true,
... | {
return;
} | conditional_block |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
us... | image_green,
image_blue,
}
}
let ids = Ids::new(ui.widget_id_generator());
let texture = graphics.load_texture_from_image::<ColorFormat>("resources/cloud.png");
let image_map = image_map! {
(ids.image_red, texture.clone()),
(ids.image_green, te... | {
let builder = WindowBuilder::new()
.with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (2, 1)))
.with_title("Conrod".to_string())
.with_dimensions(512, 512);
let (window, mut graphics) = Graphics::new(builder);
let mut renderer = Renderer::new(window.hidpi_factor(), &... | identifier_body |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
us... |
}
{
let mut ui = &mut ui.set_widgets();
use conrod::{Colorable, Positionable, Sizeable, Widget};
widget::Canvas::new().color(conrod::color::DARK_CHARCOAL).set(ids.canvas, ui);
let demo_text = "Lorem ipsum dolor sit amet, consectetur adipiscing... | {
ui.handle_event(event);
} | conditional_block |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
us... | let delta_time = frameclock.reset();
if let Some(fps_sample) = fps_counter.update(delta_time) {
mspf = 1000. / fps_sample;
fps = fps_sample as u32;
}
for event in window.poll_events() {
match event {
Event::KeyboardInput(_, _, ... | let mut fps = 0;
'main: loop {
| random_line_split |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
us... | () {
let builder = WindowBuilder::new()
.with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (2, 1)))
.with_title("Conrod".to_string())
.with_dimensions(512, 512);
let (window, mut graphics) = Graphics::new(builder);
let mut renderer = Renderer::new(window.hidpi_factor(), &... | main | identifier_name |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate l... | println!("");
println!("Usage:");
println!(" {} [OPTIONS] NAME...", NAME);
println!("");
print!("{}", getopts::usage("Create a FIFO with the given name.", opts.as_slice()).as_slice());
if matches.free.is_empty() {
return 1;
}
return 0;
}
... |
if matches.opt_present("help") || matches.free.is_empty() {
println!("{} {}", NAME, VERSION); | random_line_split |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate l... | (args: Vec<String>) -> int {
let opts = [
getopts::optopt("m", "mode", "file permissions for the fifo", "(default 0666)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match get... | uumain | identifier_name |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate l... |
let mode = match matches.opt_str("m") {
Some(m) => match FromStrRadix::from_str_radix(m.as_slice(), 8) {
Some(m) => m,
None => {
show_error!("invalid mode");
return 1;
}
},
None => 0o666,
};
let mut exit_status = ... | {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS] NAME...", NAME);
println!("");
print!("{}", getopts::usage("Create a FIFO with the given name.", opts.as_slice()).as_slice());
if matches.free.is_empty() {
r... | conditional_block |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate l... | println!("Usage:");
println!(" {} [OPTIONS] NAME...", NAME);
println!("");
print!("{}", getopts::usage("Create a FIFO with the given name.", opts.as_slice()).as_slice());
if matches.free.is_empty() {
return 1;
}
return 0;
}
let mode = match m... | {
let opts = [
getopts::optopt("m", "mode", "file permissions for the fifo", "(default 0666)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), ... | identifier_body |
visible-private-types-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
fn dummy(&self) { }
}
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
... | // 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 | random_line_split |
visible-private-types-generics.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 ... | <
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
x: T
}
pub struct S2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
x: T
}
pub enum E1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
V1(T)
}
pub enum E2<T> w... | S1 | identifier_name |
ip_utils.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.... | return Some(NodeEndpoint { address: SocketAddr::V4(SocketAddrV4::new(external_addr, tcp_port)), udp_port: udp_port });
},
}
},
}
},
}
},
}
}
None
}
#[test]
fn can_select_public_address() {
let pub_address = select_public_address(40477);
assert!(pub_address.por... | {
if let SocketAddr::V4(ref local_addr) = local.address {
match search_gateway_from_timeout(local_addr.ip().clone(), Duration::new(5, 0)) {
Err(ref err) => debug!("Gateway search error: {}", err),
Ok(gateway) => {
match gateway.get_external_ip() {
Err(ref err) => {
debug!("IP request error: {}",... | identifier_body |
ip_utils.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.... | for addr in &list { //TODO: use better criteria than just the first in the list
match *addr {
IpAddr::V4(a) if!a.is_unspecified_s() &&!a.is_loopback() &&!a.is_link_local() => {
return SocketAddr::V4(SocketAddrV4::new(a, port));
},
_ => {},
}
}
for addr in list {
match addr {
... | pub fn select_public_address(port: u16) -> SocketAddr {
match get_if_addrs() {
Ok(list) => {
//prefer IPV4 bindings | random_line_split |
ip_utils.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.... | }
},
}
}
,
}
}
None
}
#[test]
fn can_select_public_address() {
let pub_address = select_public_address(40477);
assert!(pub_address.port() == 40477);
}
#[ignore]
#[test]
fn can_map_external_address_or_fail() {
let pub_address = select_public_address(40478);
let _ = map_external_address(&NodeE... | {
match gateway.get_external_ip() {
Err(ref err) => {
debug!("IP request error: {}", err);
},
Ok(external_addr) => {
match gateway.add_any_port(PortMappingProtocol::TCP, SocketAddrV4::new(local_addr.ip().clone(), local_addr.port()), 0, "Parity Node/TCP") {
Err(ref err) => {
... | conditional_block |
ip_utils.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | () {
let pub_address = select_public_address(40477);
assert!(pub_address.port() == 40477);
}
#[ignore]
#[test]
fn can_map_external_address_or_fail() {
let pub_address = select_public_address(40478);
let _ = map_external_address(&NodeEndpoint { address: pub_address, udp_port: 40478 });
}
#[test]
fn ipv4_properties... | can_select_public_address | identifier_name |
genesis.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | /// Timestamp.
pub timestamp: u64,
/// Parent hash.
pub parent_hash: H256,
/// Gas limit.
pub gas_limit: U256,
/// Transactions root.
pub transactions_root: H256,
/// Receipts root.
pub receipts_root: H256,
/// State root.
pub state_root: Option<H256>,
/// Gas used.
pub gas_used: U256,
/// Extra data.
p... | /// Author.
pub author: Address, | random_line_split |
genesis.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
/// Seal.
pub seal: Seal,
/// Difficulty.
pub difficulty: U256,
/// Author.
pub author: Address,
/// Timestamp.
pub timestamp: u64,
/// Parent hash.
pub parent_hash: H256,
/// Gas limit.
pub gas_limit: U256,
/// Transactions root.
pub transactions_root: H256,
/// Receipts root.
pub receipts_root: H25... | Genesis | identifier_name |
accept_language.rs | use language_tags::LanguageTag;
use header::QualityItem;
header! {
/// `Accept-Language` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
///
/// The `Accept-Language` header field can be used by user agents to
/// indicate the set of natural languages that are pre... | /// # fn main() {
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptLanguage(vec![
/// qitem(langtag!(da)),
/// QualityItem::new(langtag!(en;;;GB), Quality(800)),
/// QualityItem::new(langtag!(en), Quality(700)),
/// ])
/// );
/// # ... | /// # | random_line_split |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (fname: String) -> MmapMut {
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&fname)
.expect("failed to open file");
file.set_len((NSAMPLES * NN * 8) as u64)
.expect("failed to set length");
return unsafe { ... | ropen | identifier_name |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | }
}
let end = jumble(buffer);
for i in 0..NN {
for k in 0..8 {
endb[j * NN * 8 + i * 8 + k] = (end[i] >> k * 8) as u8;
}
}
}
startb.flush().expect("failed to flush");
endb.flush().expect("failed to flush");
} | for k in 0..8 {
startb[j * NN * 8 + i * 8 + k] = (buffer[i] >> k * 8) as u8; | random_line_split |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
return state;
}
use std::fs::File;
use std::io::prelude::*;
use memmap::MmapMut;
fn ropen(fname: String) -> MmapMut {
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&fname)
.expect("failed to open file");
... | {
state[0] ^= state[NN - 1];
i = 1;
} | conditional_block |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | }
}
startb.flush().expect("failed to flush");
endb.flush().expect("failed to flush");
}
| {
let mut rng = thread_rng();
let mut startb = ropen("start".to_string());
let mut endb = ropen("end".to_string());
for j in 0..NSAMPLES {
if j % 100 == 0 {
println!("{:?}", j);
}
let mut buffer = [0u64; NN];
for i in 0..NN {
buffer[i] = rng.next_u... | identifier_body |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option... | (*node).elem == e
},
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
... | } | random_line_split |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn | (e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option<Box<Node>>,
tail: Option<Shared<Node>>
}
#[allow(boxed_local)]
impl Queue {
pub fn new() -> Queue {
Queue {
size: 0,
... | new | identifier_name |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option... | ,
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
}
)
}
}
| {
let mut node = head;
while (*node).elem != e && (*node).next.is_some() {
node = (*node).next.as_ref().unwrap();
}
(*node).elem == e
} | conditional_block |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option... |
pub fn enqueue(&mut self, e: i32) {
self.size += 1;
let mut node = Box::new(Node::new(e));
let raw: *mut _ = &mut *node;
match self.tail {
Some(share) => unsafe { (**share).next = Some(node) },
None => self.head = Some(node),
}
unsafe {
... | {
self.size
} | identifier_body |
server.rs | extern crate iron;
extern crate handlebars_iron as hbs;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::{status};
use hbs::{Template, HandlebarsEngine};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
struct Team {
name: String,
pts: u16
}
impl ToJson for Team {
f... | m.to_json()
}
}
fn make_data () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Gu... | random_line_split | |
server.rs | extern crate iron;
extern crate handlebars_iron as hbs;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::{status};
use hbs::{Template, HandlebarsEngine};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
struct Team {
name: String,
pts: u16
}
impl ToJson for Team {
f... | () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Guoan".to_string(),
... | make_data | identifier_name |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sp... |
}
#[cfg(test)]
mod test {
use na::Vec3;
use na;
use super::SpacializedCone;
use bounding_volume::{BoundingVolume, BoundingSphere};
#[test]
#[cfg(feature = "3d")]
fn test_merge_vee() {
let sp = BoundingSphere::new(na::orig(), na::one());
let pi: N = BaseFloat::pi();
... | {
self.sphere.set_translation(v)
} | identifier_body |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sp... |
}
#[inline]
fn merged(&self, other: &SpacializedCone) -> SpacializedCone {
let mut res = self.clone();
res.merge(other);
res
}
}
impl Translation<Vect> for SpacializedCone {
#[inline]
fn translation(&self) -> Vect {
self.sphere.center().as_vec().clone()
}... | {
// This happens if alpha ~= 0 or alpha ~= pi.
if alpha > na::one() { // NOTE: 1.0 is just a randomly chosen number in-between 0 and pi.
// alpha ~= pi
self.hangle = alpha;
}
else {
// alpha ~= 0, do nothing.
}
... | conditional_block |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sp... |
let ab = a.merged(&b);
assert!(na::approx_eq(&ab.hangle, &(pi_12 * na::cast(4.0f64))))
}
} | random_line_split | |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sp... | (&self) -> Vect {
self.sphere.center().as_vec().clone()
}
#[inline]
fn inv_translation(&self) -> Vect {
-self.sphere.translation()
}
#[inline]
fn append_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv);
}
#[inline]
fn append_translatio... | translation | identifier_name |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
pub fn main() {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// A... | println!("Slice: {:?}", &ps[1.. 4]);
} |
let ps: &[i32] = &[1, 3, 5, 6, 9];
analyze_slice(&ps[1 .. 4]); | random_line_split |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) |
pub fn main() {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [i32; 500] = [0; 500];
println!("Array xs: {:?}", xs);
// Indexing starts at 0
println!("first element of the array: {}", ... | {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
} | identifier_body |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
pub fn | () {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [i32; 500] = [0; 500];
println!("Array xs: {:?}", xs);
// Indexing starts at 0
println!("first element of the array: {}", xs[0]);
p... | main | identifier_name |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... |
}
pub fn command() -> App<'static,'static> {
SubCommand::with_name("log").about("View repository commit history.")
}
pub fn go(repository: &mut Repository, _matches: &ArgMatches) -> Result<()> {
let mut commits = {
let ctx = repository.local(())?;
let mut commits = BinaryHeap::new();
... | {
self.commit.timestamp.cmp(&other.commit.timestamp)
} | identifier_body |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... | for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
} | }
| random_line_split |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... | (&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TimeOrdered {
fn cmp(&self, other: &Self) -> Ordering {
self.commit.timestamp.cmp(&other.commit.timestamp)
}
}
pub fn command() -> App<'static,'static> {
SubCommand::with_name("log").about("View reposi... | partial_cmp | identifier_name |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: Objec... |
for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
}
| {
write!(
buf,
"commit {} \nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
} | conditional_block |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... |
Err(TryLockError::Poisoned(err)) => {
d.field("data", &&**err.get_ref());
}
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'... | {
d.field("data", &&*guard);
} | conditional_block |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... | (&mut self) -> LockResult<&mut T> {
let data = self.data.get_mut();
poison::map_result(self.poison.borrow(), |_| data)
}
}
#[stable(feature = "mutex_from", since = "1.24.0")]
impl<T> From<T> for Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
/// This is equivalent to... | get_mut | identifier_name |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... |
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then [`Err`] is returned.
/// Otherwise, an RAII guard is returned. The lock will be unlocked when the
/// guard is dropped.
///
/// This function does not block.
///
/// # Errors
///
... | {
unsafe {
self.inner.raw_lock();
MutexGuard::new(self)
}
} | identifier_body |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
//... | #[stable(feature = "rust1", since = "1.0.0")]
pub struct MutexGuard<'a, T:?Sized + 'a> {
lock: &'a Mutex<T>,
poison: poison::Guard,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Send for MutexGuard<'_, T> {}
#[stable(feature = "mutexguard", since = "1.19.0")]
unsafe impl<T:?Sized + Sync> Sync ... | not(bootstrap),
must_not_suspend = "holding a MutexGuard across suspend \
points can cause deadlocks, delays, \
and cause Futures to not implement `Send`"
)] | random_line_split |
pretty.rs | // Pris -- A language for designing slides
// Copyright 2017 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! The string formatting prim... |
pub fn print<P: Print>(&mut self, content: P) {
content.print(self);
}
pub fn println<P: Print>(&mut self, content: P) {
for _ in 0..self.indent * 2 {
self.target.push(' ');
}
self.print(content);
}
pub fn print_hex_byte(&mut self, content: u8) {
... | {
assert!(self.indent > 0);
self.indent -= 1;
} | identifier_body |
pretty.rs | // Pris -- A language for designing slides
// Copyright 2017 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! The string formatting prim... | write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for usize {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for f64 {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Format... | fn print(&self, f: &mut Formatter) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.