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 |
|---|---|---|---|---|
simple.rs | use stb_truetype::FontInfo;
use std::borrow::Cow;
fn main() {
let file = include_bytes!("../fonts/Gudea-Regular.ttf") as &[u8];
let font = FontInfo::new(Cow::Borrowed(file), 0).unwrap();
let vmetrics = font.get_v_metrics();
println!("{:?}", vmetrics);
let c = '\\';
let cp = c as u32;
let g ... | println!("{:?}", advance);
let scale = font.scale_for_pixel_height(20.0);
println!("{:?}", scale);
} | println!("{:?}", hmetrics);
let advance = font.get_codepoint_kern_advance('f' as u32, 'f' as u32); | random_line_split |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T:'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<Fn... |
})
}
#[cfg(test)]
#[cfg(not(feature = "inclusive_range"))]
mod tests {
use super::*;
// range
#[test]
pub fn range_valid() {
assert!(range(1, 100)(&1).is_ok());
assert!(range(1, 100)(&50).is_ok());
assert!(range(1, 100)(&100).is_ok());
}
#[test]
pub fn range_... | {
Err(::Invalid {
msg: "Must be in the range %1..%2.".to_string(),
args: vec![start.to_string(), end.to_string()],
human_readable: format!("Must be between {} and {}", start, end)
})
} | conditional_block |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T:'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<Fn... | () {
assert!(range(1, 100)(&1).is_ok());
assert!(range(1, 100)(&50).is_ok());
assert!(range(1, 100)(&100).is_ok());
}
#[test]
pub fn range_invalid() {
assert!(range(1, 100)(&0).is_err());
assert!(range(1, 100)(&101).is_err());
}
}
#[cfg(test)]
#[cfg(feature = "i... | range_valid | identifier_name |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T:'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<Fn... | }
#[cfg(test)]
#[cfg(not(feature = "inclusive_range"))]
mod tests {
use super::*;
// range
#[test]
pub fn range_valid() {
assert!(range(1, 100)(&1).is_ok());
assert!(range(1, 100)(&50).is_ok());
assert!(range(1, 100)(&100).is_ok());
}
#[test]
pub fn range_invalid... | {
// do bounds checking here so we can panic early if needed
if range.end() <= range.start() {
panic!("Invalid range!"); // TODO: Bad way to do this.
}
Box::new(move |s: &T| {
let start = range.start();
let end = range.end();
if *s >= *start && *s <= *end {
... | identifier_body |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T:'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<Fn... | pub fn range_invalid() {
assert!(range(1..=100)(&0).is_err());
assert!(range(1..=100)(&101).is_err());
}
} | random_line_split | |
main.rs | #![crate_name = "rduperemove"]
#![feature(plugin)]
#![feature(io, os, collections, path)]
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
extern crate btrfs;
extern crate crypto;
extern crate deque;
#[macro_use]
extern crate log;
#[plugin] #[no_link]
extern crate docopt_macros;
use std::old... | {
base_dirs: Vec<Path>,
worker_count: usize,
min_file_size: usize,
}
docopt!(CommandLineOptions, "
rduperemove - Whole-file deduplication for BTRFS filesystems on (Linux 3.13+).
Usage: rduperemove [options] <path>...
rduperemove (-h|--help)
Options:
<path>... On... | Configuration | identifier_name |
main.rs | #![crate_name = "rduperemove"]
#![feature(plugin)]
#![feature(io, os, collections, path)]
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
extern crate btrfs;
extern crate crypto;
extern crate deque;
#[macro_use]
extern crate log;
#[plugin] #[no_link]
extern crate docopt_macros;
use std::old... | docopt!(CommandLineOptions, "
rduperemove - Whole-file deduplication for BTRFS filesystems on (Linux 3.13+).
Usage: rduperemove [options] <path>...
rduperemove (-h|--help)
Options:
<path>... One or more directories (on the same btrfs filesystem) \
... | }
| random_line_split |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn main() {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetcher's... | for (i, item) in conf.get_latest_entry_names().iter().enumerate() {
println!("{} latest entry name: {}", i, item);
}
}
_ => println!("Given invalid option!"),
}
}
... | 6 => { | random_line_split |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn main() |
println!("Loaded podstats!");
let conf_file = match matches.value_of("config") {
Some(c) => Some(c.to_string()),
None => None,
};
let mut conf = config::Config::new(conf_file);
conf.load_cache();
let prompt = util::Prompt {};
let mut menu_options = Vec::new();
menu_o... | {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetcher's msgpack cache and provides stats.")
.arg(
Arg::with_name("config")
.short("c")
.long("config")
... | identifier_body |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn main() {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetcher's... |
5 => {
for (i, item) in conf.get_earliest_entry_names().iter().enumerate() {
println!("{} earliest entry name: {}", i, item);
}
}
6 => {
for (i, item) in conf.... | {
let item = conf.get_highest_entry_count_sub_name();
println!("Name of sub with highest entry count: {}", item);
} | conditional_block |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn | () {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetcher's msgpack cache and provides stats.")
.arg(
Arg::with_name("config")
.short("c")
.long("config")
... | main | identifier_name |
types.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::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings:... | (&self) -> u32 {
use self::TexFormat::*;
match *self {
DepthComponent => 1,
Alpha => 1,
Luminance => 1,
LuminanceAlpha => 2,
RGB => 3,
RGBA => 4,
}
}
}
| components | identifier_name |
types.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::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings:... | }
}
}
type_safe_wrapper! { TexFormat,
DepthComponent => constants::DEPTH_COMPONENT,
Alpha => constants::ALPHA,
RGB => constants::RGB,
RGBA => constants::RGBA,
Luminance => constants::LUMINANCE,
LuminanceAlpha => constants::LUMINANCE_ALPHA,
}
impl TexFormat {
/// Returns how man... | Float => 1,
HalfFloat => 1, | random_line_split |
types.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::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings:... |
/// Returns how many components a single element may hold. For example, a
/// UnsignedShort4444 holds four components, each with 4 bits of data.
pub fn components_per_element(&self) -> u32 {
use self::TexDataType::*;
match *self {
UnsignedByte => 1,
UnsignedShort565... | {
use self::TexDataType::*;
match *self {
UnsignedByte => 1,
UnsignedShort4444 | UnsignedShort5551 | UnsignedShort565 => 2,
Float => 4,
HalfFloat => 2,
}
} | identifier_body |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... |
make_free_fn!(fst_regex_free, *mut Regex);
| {
let pat = cstr_to_str(c_pat);
let re = with_context!(ctx, ptr::null_mut(), Regex::new(pat));
to_raw_ptr(re)
} | identifier_body |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... |
if!self.error_display.is_null() {
fst_string_free(self.error_display);
}
if!self.error_description.is_null() {
fst_string_free(self.error_description);
}
}
}
pub fn cstr_to_str<'a>(s: *mut libc::c_char) -> &'a str {
let cstr = unsafe { CStr::from_ptr(s)... | {
fst_string_free(self.error_debug);
} | conditional_block |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... | (&mut self) {
self.has_error = false;
if!self.error_type.is_null() {
fst_string_free(self.error_type);
}
if!self.error_debug.is_null() {
fst_string_free(self.error_debug);
}
if!self.error_display.is_null() {
fst_string_free(self.error_d... | clear | identifier_name |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... | CString::new(string).unwrap().into_raw()
}
pub fn to_raw_ptr<T>(v: T) -> *mut T {
Box::into_raw(Box::new(v))
}
// FIXME: This requires the nightly channel, isn't there a better way to
// get this information?
pub fn get_typename<T>(_: &T) -> &'static str {
unsafe { intrinsics::type_name::<T>() }
}
... | pub fn str_to_cstr(string: &str) -> *mut libc::c_char { | random_line_split |
memcache.rs | use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{Arc, Mutex};
pub struct MemCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone + Send,
{
map: Mutex<HashMap<K, Arc<Mutex<Option<V>>>>>,
}
impl<K, V> Default for MemCache<K, V>
where
K: Eq + Hash + C... | () -> Self {
MemCache {
map: Mutex::new(HashMap::new()),
}
}
}
impl<K, V> MemCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone + Send,
{
pub fn run_cached<F>(&self, key: K, worker: F) -> V
where
F: Fn(Option<V>) -> V,
{
// Get/create lock for cache ent... | default | identifier_name |
memcache.rs | use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{Arc, Mutex};
pub struct MemCache<K, V>
where
K: Eq + Hash + Clone,
V: Clone + Send,
{
map: Mutex<HashMap<K, Arc<Mutex<Option<V>>>>>,
}
impl<K, V> Default for MemCache<K, V>
where
K: Eq + Hash + C... | let value = worker(entry.take());
*entry = Some(value.clone());
value
}
Err(e) => panic!("Mutex error: {}", e),
}
}
} | Ok(mut entry) => { | random_line_split |
version.rs | use std::str::CharIndices;
use std::iter::Peekable;
use std::cmp::Ordering;
use std::default::Default;
use quire::validate as V;
use quire::ast::{Ast, NullKind, Tag};
use quire::{Error as QuireError, ErrorCollector};
pub struct Version<'a>(pub &'a str);
pub struct Components<'a>(&'a str, Peekable<CharIndices<'a>>);
... | while let Some(&(_, x)) = self.1.peek() {
if x.is_alphanumeric() { break; }
self.1.next();
}
if let Some(&(start, x)) = self.1.peek() {
if x.is_numeric() {
while let Some(&(_, x)) = self.1.peek() {
if!x.is_numeric() { break;... | type Item = Component<'a>;
fn next(&mut self) -> Option<Component<'a>> {
use self::Component::*; | random_line_split |
version.rs | use std::str::CharIndices;
use std::iter::Peekable;
use std::cmp::Ordering;
use std::default::Default;
use quire::validate as V;
use quire::ast::{Ast, NullKind, Tag};
use quire::{Error as QuireError, ErrorCollector};
pub struct Version<'a>(pub &'a str);
pub struct Components<'a>(&'a str, Peekable<CharIndices<'a>>);
... | () {
assert!(Version("v0.4.1-28-gfba00d7") > Version("v0.4.1"));
assert!(Version("v0.4.1-28-gfba00d7") > Version("v0.4.1-27-gtest"));
assert!(Version("v0.4.1-28-gfba00d7") < Version("v0.4.2"));
}
#[test]
fn test_version_cmp2() {
assert!(!(Version("v0.4.1-172-ge011471")
... | test_version_cmp | identifier_name |
version.rs | use std::str::CharIndices;
use std::iter::Peekable;
use std::cmp::Ordering;
use std::default::Default;
use quire::validate as V;
use quire::ast::{Ast, NullKind, Tag};
use quire::{Error as QuireError, ErrorCollector};
pub struct Version<'a>(pub &'a str);
pub struct Components<'a>(&'a str, Peekable<CharIndices<'a>>);
... |
pub fn current_version(mut self, version: String) -> MinimumVagga {
self.current_version = Some(version);
self
}
}
impl V::Validator for MinimumVagga {
fn default(&self, pos: V::Pos) -> Option<Ast> {
if self.optional {
Some(Ast::Null(pos.clone(), Tag::NonSpecific, NullK... | {
self.optional = true;
self
} | identifier_body |
dispatcher.rs | //! HTTP Service Dispatcher
use std::{io, net::SocketAddr, str::FromStr, sync::Arc};
use hyper::{
header::{GetAll, HeaderValue},
http::uri::{Authority, Scheme},
upgrade,
Body,
HeaderMap,
Method,
Request,
Response,
StatusCode,
Uri,
Version,
};
use log::{debug, error, trace};... | (mut self) -> io::Result<Response<Body>> {
trace!("request {} {:?}", self.client_addr, self.req);
// Parse URI
//
// Proxy request URI must contains a host
let host = match host_addr(self.req.uri()) {
None => {
if self.req.uri().authority().is_some() ... | dispatch | identifier_name |
dispatcher.rs | //! HTTP Service Dispatcher
use std::{io, net::SocketAddr, str::FromStr, sync::Arc};
use hyper::{
header::{GetAll, HeaderValue},
http::uri::{Authority, Scheme},
upgrade,
Body,
HeaderMap,
Method,
Request,
Response,
StatusCode,
Uri,
Version,
};
use log::{debug, error, trace}; |
use crate::local::{
context::ServiceContext,
loadbalancing::PingBalancer,
net::AutoProxyClientStream,
utils::establish_tcp_tunnel,
};
use super::{
client_cache::ProxyClientCache,
http_client::{BypassHttpClient, HttpClientEnum},
utils::{authority_addr, host_addr},
};
pub struct HttpDispatc... |
use shadowsocks::relay::socks5::Address; | random_line_split |
dispatcher.rs | //! HTTP Service Dispatcher
use std::{io, net::SocketAddr, str::FromStr, sync::Arc};
use hyper::{
header::{GetAll, HeaderValue},
http::uri::{Authority, Scheme},
upgrade,
Body,
HeaderMap,
Method,
Request,
Response,
StatusCode,
Uri,
Version,
};
use log::{debug, error, trace};... | else {
trace!("proxied {} -> {} {:?}", self.client_addr, host, self.req);
// Keep connections for clients in ServerScore::client
// client instance is kept for Keep-Alive connections
let server = self.balancer.best_tcp_server();
HttpClien... | {
trace!("bypassed {} -> {} {:?}", self.client_addr, host, self.req);
HttpClientEnum::Bypass(self.bypass_client)
} | conditional_block |
dispatcher.rs | //! HTTP Service Dispatcher
use std::{io, net::SocketAddr, str::FromStr, sync::Arc};
use hyper::{
header::{GetAll, HeaderValue},
http::uri::{Authority, Scheme},
upgrade,
Body,
HeaderMap,
Method,
Request,
Response,
StatusCode,
Uri,
Version,
};
use log::{debug, error, trace};... |
pub async fn dispatch(mut self) -> io::Result<Response<Body>> {
trace!("request {} {:?}", self.client_addr, self.req);
// Parse URI
//
// Proxy request URI must contains a host
let host = match host_addr(self.req.uri()) {
None => {
if self.req.u... | {
HttpDispatcher {
context,
req,
balancer,
client_addr,
bypass_client,
proxy_client_cache,
}
} | identifier_body |
text_run.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::{Font, RunMetrics, FontMetrics};
use servo_util::geometry::Au;
use servo_util::range::Range;
use servo_u... | };
// Create a glyph store for this slice if it's nonempty.
if can_break_before && byte_i > byte_last_boundary {
let slice = text.slice(byte_last_boundary, byte_i).to_string();
debug!("creating glyph store for slice {} (ws? {}), {} - {} in run {}",
... | _ => false
} | random_line_split |
text_run.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::{Font, RunMetrics, FontMetrics};
use servo_util::geometry::Au;
use servo_util::range::Range;
use servo_u... | (&self, range: &Range<CharIndex>) -> Au {
// TODO(Issue #199): alter advance direction for RTL
// TODO(Issue #98): using inter-char and inter-word spacing settings when measuring text
self.iter_slices_for_range(range)
.fold(Au(0), |advance, (glyphs, _, slice_range)| {
... | advance_for_range | identifier_name |
text_run.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::{Font, RunMetrics, FontMetrics};
use servo_util::geometry::Au;
use servo_util::range::Range;
use servo_u... |
}
} else {
match ch {
'' | '\t' | '\n' => {
cur_slice_is_whitespace = true;
true
},
_ => false
}
};
// Create a glyph store for... | {
cur_slice_is_whitespace = false;
true
} | conditional_block |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... | (&mut self, event: &piston::input::Event,
resources: &mut Resources) -> StateTransition
{
// Convert the piston event to a conrod event.
let window_size = resources.window.size();
if let Some(ce) = conrod::backend::piston::event::convert(
event.clone(), window... | handle_event | identifier_name |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... |
}
impl PauseMenu {
pub fn new(resources: &mut Resources) -> PauseMenu {
let window_size = resources.window.size();
// Construct our `Ui`.
let mut ui = conrod::UiBuilder::new([window_size.width as f64,
window_size.height as f64])
.bui... | {
write!(f, "PauseMenu")
} | identifier_body |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... | else if conrod::widget::Button::new()
.down(15.0)
.w_h(80.0, 25.0)
.label("Quit")
.set(self.widget_ids.quit, ui)
.was_clicked()
{
StateTransition::Quit
} else {
StateTransition::Continue
}
}
fn update(&mut s... | {
StateTransition::End
} | conditional_block |
pausemenu.rs | use std::fmt::{self, Debug, Formatter};
use std::path::Path;
use conrod::{self, Labelable, Positionable, Sizeable, Widget};
use piston;
use piston::window::Window;
use piston_window::{self, Context, G2d, G2dTexture};
use piston_window::texture::UpdateTexture;
use ::{GameState, Resources, StateTransition};
widget_ids... | {
StateTransition::End
} else if conrod::widget::Button::new()
.down(15.0)
.w_h(80.0, 25.0)
.label("Quit")
.set(self.widget_ids.quit, ui)
.was_clicked()
{
StateTransition::Quit
} else {
StateTransi... | .mid_top_of(self.widget_ids.canvas)
.w_h(80.0, 25.0)
.label("Resume")
.set(self.widget_ids.resume, ui)
.was_clicked() | random_line_split |
parallel.rs | and records.
//!
//! Sequences are read and processed in batches (`RecordSet`) because sending
//! data across channels has a performance impact. The process works as follows:
//!
//! * Sequence parsing is done in a background thread
//! * Record sets are sent to worker threads, where expensive operations take
//! p... | <R, Ri, W, F, O, Out, E>(
reader_init: Ri,
n_workers: u32,
queue_len: usize,
work: W,
mut func: F,
) -> Result<Option<Out>, E>
where
R: RecordSetReader,
Ri: Send + FnOnce() -> Result<R, E>,
R::RecordSet: Default + Send,
for<'a> &'a R::RecordSet: IntoIterator + Send,
O: Default + ... | read_process_records_init | identifier_name |
parallel.rs | sets and records.
//!
//! Sequences are read and processed in batches (`RecordSet`) because sending
//! data across channels has a performance impact. The process works as follows:
//!
//! * Sequence parsing is done in a background thread
//! * Record sets are sent to worker threads, where expensive operations take
//... | return Ok(Some(out));
}
}
}
Ok(None)
},
)
.and_then(From::from)
}
macro_rules! impl_parallel_reader {
($($l:lifetime)?; $SeqReader:ty, $RecordPositionTrait:path, $RecordSet:ty, $Error:ty, $read_fn:ident) => {
... | {
read_process_recordsets_init(
reader_init,
n_workers,
queue_len,
|rset, out: &mut Vec<O>| {
let mut record_iter = rset.into_iter();
for mut d in (&mut record_iter).zip(out.iter_mut()) {
work(d.0, &mut d.1);
}
for recor... | identifier_body |
parallel.rs | record sets and records.
//!
//! Sequences are read and processed in batches (`RecordSet`) because sending
//! data across channels has a performance impact. The process works as follows:
//!
//! * Sequence parsing is done in a background thread
//! * Record sets are sent to worker threads, where expensive operations ... | || Ok(reader), n_workers, queue_len, work, func
);
out
}
/// Like
#[doc = $name_link]
///, but instead of a [`RecordSetReader`](RecordSetReader), it takes a
/// closure (`reader_init`) returning an `RecordSetReader` instance.
/// T... | W: Send + Sync + Fn($Record, &mut O),
F: FnMut($Record, &mut O) -> Option<Out>,
{
let out: Result<_, $Error> = $name_init( | random_line_split |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... |
tomas_wang_hash(key_from_pair(ia, ib))
}
}
/// Hash function for `usize`.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintTWHash { unused: usize } // FIXME: ICE if the struct is zero-sized
impl UintTWHash {
/// Creates a new UintTWHash.
pub fn new() -> UintTWHash {
UintTW... | {
mem::swap(&mut ia, &mut ib)
} | conditional_block |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... | let mut ib = b;
if ia > ib {
mem::swap(&mut ia, &mut ib)
}
tomas_wang_hash(key_from_pair(ia, ib))
}
}
/// Hash function for `usize`.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintTWHash { unused: usize } // FIXME: ICE if the struct is zero-sized
impl... | random_line_split | |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... |
}
/// Hash function for `usize`.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintTWHash { unused: usize } // FIXME: ICE if the struct is zero-sized
impl UintTWHash {
/// Creates a new UintTWHash.
pub fn new() -> UintTWHash {
UintTWHash { unused: 0 }
}
}
impl HashFun<usize> for Ui... | {
let mut ia = a;
let mut ib = b;
if ia > ib {
mem::swap(&mut ia, &mut ib)
}
tomas_wang_hash(key_from_pair(ia, ib))
} | identifier_body |
hash.rs | //! Trait for hash functions.
use std::mem;
use std::num::Wrapping;
/// Hash function.
pub trait HashFun<K> {
/// Hash function.
fn hash(&self, &K) -> usize;
}
/// Hash function for pairs of `usize`, using the Tomas Wang hash.
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct UintPairTWHash { unuse... | (a: usize, b: usize) -> usize {
(a & 0xffffffff) | (b << 32)
}
// http://www.concentric.net/~Ttwang/tech/inthash.htm -- dead link!
// (this one works: http://naml.us/blog/tag/thomas-wang)
/// Tomas Wang integer hash function.
#[cfg(target_pointer_width = "64")] #[inline]
pub fn tomas_wang_hash(k: usize) -> usize {... | key_from_pair | identifier_name |
apple_ios_base.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 ... | &Armv7 => "armv7",
&Armv7s => "armv7s",
&Arm64 => "arm64",
&I386 => "i386",
&X86_64 => "x86_64"
}
}
}
pub fn get_sdk_root(sdk_name: &str) -> String {
let res = Command::new("xcrun")
.arg("--show-sdk-path")
... | impl Arch {
pub fn to_string(&self) -> &'static str {
match self { | random_line_split |
apple_ios_base.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 ... | {
TargetOptions {
cpu: target_cpu(arch),
dynamic_linking: false,
executables: true,
// Although there is an experimental implementation of LLVM which
// supports SS on armv7 it wasn't approved by Apple, see:
// http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-M... | identifier_body | |
apple_ios_base.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 ... | (arch: Arch) -> String {
match arch {
Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher
Armv7s => "cortex-a9",
Arm64 => "cyclone",
I386 => "generic",
X86_64 => "x86-64",
}.to_string()
}
pub fn opts(arch: Arch) -> TargetOptions {
TargetOptions {
... | target_cpu | identifier_name |
node.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... | match event {
::event::Event::Request{ request, our_authority, from_authority, response_token } =>
self.handle_request(request, our_authority, from_authority, response_token),
// Event::Response{ response, our_authority, from_authority } =>
... | debug!("Node: Received event {:?}", event); | random_line_split |
node.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... | ,
}
}
fn handle_get_request(&mut self, data_request: ::data::DataRequest,
our_authority: ::authority::Authority,
from_authority: ::authority::Authority,
response_token: Option<::SignedToken>) ... | {
debug!("Node: Delete unimplemented.");
} | conditional_block |
node.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... | () -> Node {
let (sender, receiver) = ::std::sync::mpsc::channel::<::event::Event>();
let routing = ::routing::Routing::new(sender);
Node {
routing: routing,
receiver: receiver,
db: ::std::collections::BTreeMap::new(),
}
}
pub fn run(&mut sel... | new | identifier_name |
node.rs | // Copyright 2015 MaidSafe.net limited.
//
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// ... |
pub fn run(&mut self) {
while let Ok(event) = self.receiver.recv() {
debug!("Node: Received event {:?}", event);
match event {
::event::Event::Request{ request, our_authority, from_authority, response_token } =>
self.handle_request(request, our_a... | {
let (sender, receiver) = ::std::sync::mpsc::channel::<::event::Event>();
let routing = ::routing::Routing::new(sender);
Node {
routing: routing,
receiver: receiver,
db: ::std::collections::BTreeMap::new(),
}
} | identifier_body |
bg.rs | use crate::builtins::utils::print_stderr_with_capture;
use crate::jobc;
use crate::libc;
use crate::shell::Shell;
use crate::types::{CommandResult, CommandLine, Command};
pub fn run(sh: &mut Shell, cl: &CommandLine, cmd: &Command,
capture: bool) -> CommandResult | if job_str.starts_with("%") {
job_str = job_str.trim_start_matches('%').to_string();
}
match job_str.parse::<i32>() {
Ok(n) => job_id = n,
Err(_) => {
let info = "cicada: bg: invalid job id";
print_stderr_with_capture(info, &mu... | {
let tokens = cmd.tokens.clone();
let mut cr = CommandResult::new();
if sh.jobs.is_empty() {
let info = "cicada: bg: no job found";
print_stderr_with_capture(info, &mut cr, cl, cmd, capture);
return cr;
}
let mut job_id = -1;
if tokens.len() == 1 {
for (gid, _)... | identifier_body |
bg.rs | use crate::builtins::utils::print_stderr_with_capture;
use crate::jobc;
use crate::libc;
use crate::shell::Shell;
use crate::types::{CommandResult, CommandLine, Command};
pub fn | (sh: &mut Shell, cl: &CommandLine, cmd: &Command,
capture: bool) -> CommandResult {
let tokens = cmd.tokens.clone();
let mut cr = CommandResult::new();
if sh.jobs.is_empty() {
let info = "cicada: bg: no job found";
print_stderr_with_capture(info, &mut cr, cl, cmd, capture);
... | run | identifier_name |
bg.rs | use crate::builtins::utils::print_stderr_with_capture;
use crate::jobc;
use crate::libc;
use crate::shell::Shell;
use crate::types::{CommandResult, CommandLine, Command};
pub fn run(sh: &mut Shell, cl: &CommandLine, cmd: &Command,
capture: bool) -> CommandResult {
let tokens = cmd.tokens.clone();
le... | } | random_line_split | |
client.rs | extern crate getopts;
use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt};
use std::string::{String};
use std::os;
use std::str;
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
fn parse_int (input: &String) -> u32 {
let val = match from_str::<u32>(input.as_slice()) {
Some(0) =... | let socket = create_client_socket (&address, &port);
//let response = make_request (socket);
make_request (socket);
} | random_line_split | |
client.rs | extern crate getopts;
use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt};
use std::string::{String};
use std::os;
use std::str;
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
fn parse_int (input: &String) -> u32 {
let val = match from_str::<u32>(input.as_slice()) {
Some(0) =... | () {
let args = os::args();
let program = args.get(0).clone();
let opts = get_program_opts ();
// bind the program options to arguments and then check
// and set parameters in the program
let matches = match getopts (args.as_slice(), opts.as_slice()) {
Ok (m) => {
if m.opt_present ("h") {
print_usage (... | main | identifier_name |
client.rs | extern crate getopts;
use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt};
use std::string::{String};
use std::os;
use std::str;
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
fn parse_int (input: &String) -> u32 {
let val = match from_str::<u32>(input.as_slice()) {
Some(0) =... |
};
let port = match matches.opt_str("p") {
Some (x) => x,
None => fail!("Failed to read the port value.")
};
let address = if matches.opt_present("a") {
matches.opt_str("a").unwrap()
} else {
let k = String::from_str("");
println!("Address is Nil, settingo setting it too: {}", k);
k
};
let socket ... | {
fail!("Failed: {}", f);
} | conditional_block |
client.rs | extern crate getopts;
use getopts::{optflag,getopts,OptGroup, usage, reqopt, optopt};
use std::string::{String};
use std::os;
use std::str;
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
fn parse_int (input: &String) -> u32 {
let val = match from_str::<u32>(input.as_slice()) {
Some(0) =... |
fn print_usage(program : String, optgroups: &[OptGroup]) {
/*
print a generated usage statement for this program
1) create the formated usage statement with the program name
2) use the str array of the resulting usage format and array of
options from the OptGroup to create the help statement.
*/
let gener... | {
// Create an array of options that will be used by
// this utility
let opts /*-> Vec<getopts::OptGroup >*/ = vec![
reqopt("p", "port", "port to listen on", "PORT"),
reqopt("a", "address", "interface to listen on", "ADDRESS"),
optflag("h", "help", "print this help menu")
];
return opts;
} | identifier_body |
lib.rs | #![crate_name = "bindgen"]
#![crate_type = "dylib"]
#![feature(quote, plugin_registrar, unboxed_closures, rustc_private, libc, std_misc, core)]
extern crate syntax;
extern crate rustc;
extern crate libc;
#[macro_use] extern crate log;
use std::collections::HashSet;
use std::default::Default;
use std::io::{Write, self... |
parser::parse(clang_opts, logger)
}
fn builtin_names() -> HashSet<String> {
let mut names = HashSet::new();
let keys = [
"__va_list_tag",
"__va_list",
"__builtin_va_list",
];
keys.iter().all(|s| {
names.insert(s.to_string());
true
});
return names;... | override_enum_ty: str_to_ikind(&options.override_enum_ty[..]),
clang_args: options.clang_args.clone(),
}; | random_line_split |
lib.rs | #![crate_name = "bindgen"]
#![crate_type = "dylib"]
#![feature(quote, plugin_registrar, unboxed_closures, rustc_private, libc, std_misc, core)]
extern crate syntax;
extern crate rustc;
extern crate libc;
#[macro_use] extern crate log;
use std::collections::HashSet;
use std::default::Default;
use std::io::{Write, self... | (self) -> Vec<P<ast::Item>> {
self.module.items
}
pub fn to_string(&self) -> String {
pprust::to_string(|s| {
s.s = pp::mk_printer(Box::new(Vec::new()), 80);
try!(s.print_mod(&self.module, &[]));
s.print_remaining_comments()
})
}
pub fn writ... | into_ast | identifier_name |
lib.rs | #![crate_name = "bindgen"]
#![crate_type = "dylib"]
#![feature(quote, plugin_registrar, unboxed_closures, rustc_private, libc, std_misc, core)]
extern crate syntax;
extern crate rustc;
extern crate libc;
#[macro_use] extern crate log;
use std::collections::HashSet;
use std::default::Default;
use std::io::{Write, self... |
pub fn to_string(&self) -> String {
pprust::to_string(|s| {
s.s = pp::mk_printer(Box::new(Vec::new()), 80);
try!(s.print_mod(&self.module, &[]));
s.print_remaining_comments()
})
}
pub fn write(&self, writer: &mut (Write +'static)) -> io::Result<()> {
... | {
self.module.items
} | identifier_body |
bounding_box.rs | use crate::cube::Cube;
use glium;
use glium::{Display, Program, Surface, implement_vertex};
use glium::index::{IndexBuffer, PrimitiveType};
use std::rc::Rc;
pub fn solid_fill_program(display: &Display) -> Program {
let vertex_shader_src = include_str!("shaders/solid.vert");
let fragment_shader_src = include_st... | }
}
pub fn draw<U>(&self, frame: &mut glium::Frame,
uniforms: &U) where U: glium::uniforms::Uniforms {
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
... | {
let vertex_data = [
Vertex { position: [c.xmin, c.ymin, c.zmin] },
Vertex { position: [c.xmax, c.ymin, c.zmin] },
Vertex { position: [c.xmax, c.ymax, c.zmin] },
Vertex { position: [c.xmin, c.ymax, c.zmin] },
Vertex { position: [c.xmin, c.ymin, c.zmax... | identifier_body |
bounding_box.rs | use crate::cube::Cube;
use glium;
use glium::{Display, Program, Surface, implement_vertex};
use glium::index::{IndexBuffer, PrimitiveType};
use std::rc::Rc;
pub fn solid_fill_program(display: &Display) -> Program {
let vertex_shader_src = include_str!("shaders/solid.vert");
let fragment_shader_src = include_st... | vertexes: glium::VertexBuffer<Vertex>,
program: Rc<Program>,
indices: IndexBuffer<u16>,
}
impl BoundingBox {
pub fn new(display: &Display, c: &Cube, program: Rc<Program>) -> BoundingBox {
let vertex_data = [
Vertex { position: [c.xmin, c.ymin, c.zmin] },
Vertex { positio... | pub struct BoundingBox { | random_line_split |
bounding_box.rs | use crate::cube::Cube;
use glium;
use glium::{Display, Program, Surface, implement_vertex};
use glium::index::{IndexBuffer, PrimitiveType};
use std::rc::Rc;
pub fn solid_fill_program(display: &Display) -> Program {
let vertex_shader_src = include_str!("shaders/solid.vert");
let fragment_shader_src = include_st... | {
vertexes: glium::VertexBuffer<Vertex>,
program: Rc<Program>,
indices: IndexBuffer<u16>,
}
impl BoundingBox {
pub fn new(display: &Display, c: &Cube, program: Rc<Program>) -> BoundingBox {
let vertex_data = [
Vertex { position: [c.xmin, c.ymin, c.zmin] },
Vertex { posi... | BoundingBox | identifier_name |
regions-infer-paramd-indirect.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 ... | (&self, b: @b<'self>) {
self.f = b;
}
fn set_f_bad(&self, b: @b) {
self.f = b; //~ ERROR mismatched types: expected `@@&'self int` but found `@@&int`
}
}
fn main() {}
| set_f_ok | identifier_name |
regions-infer-paramd-indirect.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 ... |
type a<'self> = &'self int;
type b<'self> = @a<'self>;
struct c<'self> {
f: @b<'self>
}
trait set_f {
fn set_f_ok(&self, b: @b<'self>);
fn set_f_bad(&self, b: @b);
}
impl<'self> set_f for c<'self> {
fn set_f_ok(&self, b: @b<'self>) {
self.f = b;
}
fn set_f_bad(&self, b: @b) {
... | random_line_split | |
regions-infer-paramd-indirect.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {} | identifier_body | |
server.rs | use chrono::prelude::*;
use serde::{Deserialize, Serialize};
// use eyre::{
// // eyre,
// Result,
// // Context as _,
// };
use printspool_json_store::{ Record };
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Server {
pub id: crate::DbId,
pub version: i32,
pub created_at: DateTime... | fn deleted_at_mut(&mut self) -> &mut Option<DateTime<Utc>> {
&mut self.deleted_at
}
} | random_line_split | |
server.rs | use chrono::prelude::*;
use serde::{Deserialize, Serialize};
// use eyre::{
// // eyre,
// Result,
// // Context as _,
// };
use printspool_json_store::{ Record };
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct | {
pub id: crate::DbId,
pub version: i32,
pub created_at: DateTime<Utc>,
pub deleted_at: Option<DateTime<Utc>>,
// Foreign Keys
// Props
pub name: String,
/// True if the server row is the self-reference to this instance
pub is_self: bool,
}
#[async_trait::async_trait]
impl Record f... | Server | identifier_name |
server.rs | use chrono::prelude::*;
use serde::{Deserialize, Serialize};
// use eyre::{
// // eyre,
// Result,
// // Context as _,
// };
use printspool_json_store::{ Record };
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Server {
pub id: crate::DbId,
pub version: i32,
pub created_at: DateTime... |
fn deleted_at(&self) -> Option<DateTime<Utc>> {
self.deleted_at
}
fn deleted_at_mut(&mut self) -> &mut Option<DateTime<Utc>> {
&mut self.deleted_at
}
}
| {
self.created_at
} | identifier_body |
data.rs | use std::fmt;
use std::rc::Rc;
use builtins::BuiltinFn;
use lambda::Lambda;
use scope::RcScope;
#[derive(Debug, PartialEq)]
pub enum Token
{
Lparen,
Rparen,
Quote,
Number(f64),
Ident(String),
String(String),
Error(ParseError),
End, // end of string
}
#[derive(Debug, Clone, PartialEq... | Cons{ ref car, cdr: List::Node(ref next) } => write!(f, "{} {}", car, next),
Cons{ ref car, cdr: List::End } => write!(f, "{}", car),
}
}
}
#[derive(Debug, PartialEq)]
pub enum ParseError
{
UnclosedString,
InvalidNumber,
UnclosedList,
UnexpectedRparen,
NoQuoteArg... | impl fmt::Display for Cons
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
match *self { | random_line_split |
data.rs | use std::fmt;
use std::rc::Rc;
use builtins::BuiltinFn;
use lambda::Lambda;
use scope::RcScope;
#[derive(Debug, PartialEq)]
pub enum Token
{
Lparen,
Rparen,
Quote,
Number(f64),
Ident(String),
String(String),
Error(ParseError),
End, // end of string
}
#[derive(Debug, Clone, PartialEq... |
{
Nil,
Bool(bool),
Number(f64),
Symbol(Rc<String>),
String(Rc<String>),
Builtin(Rc<BuiltinFn>),
Lambda(Rc<Lambda>),
List(List),
}
impl fmt::Display for Value
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
match *self {
Value::Nil => write!(f, "nil"... | Value | identifier_name |
tutorial-05.rs | #[macro_use]
extern crate glium;
fn main() {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new();
let display = glium::Display::new(wb, cb, &event_loo... | std::time::Duration::from_nanos(16_666_667);
*control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time);
match event {
glutin::event::Event::WindowEvent { event,.. } => match event {
glutin::event::WindowEvent::CloseRequested => {
... |
let mut t = -0.5;
event_loop.run(move |event, _, control_flow| {
let next_frame_time = std::time::Instant::now() + | random_line_split |
tutorial-05.rs | #[macro_use]
extern crate glium;
fn | () {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new();
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
#[derive(Copy, Clone)]
... | main | identifier_name |
game.rs | extern crate rustc_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable... |
pub fn size(&self) -> usize {
self.board.size()
}
pub fn to_string(&self) -> String {
self.board.to_string()
}
pub fn play_simple(&mut self, turn: &str) -> Result<Option<Player>, String> {
let player = if self.history.len() % 2 == 0 {
Player::One
} else... | {
self.check_road_winner().or(self.check_flat_winner())
} | identifier_body |
game.rs | extern crate rustc_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable... | else {
Some(player.other())
};
self.play(turn, player, owner)
}
pub fn play(&mut self, turn: &str, player: Player, owner: Option<Player>) -> Result<Option<Player>, String> {
if self.next!= player {
return Err("Not your turn".into());
}
match turn... | {
Some(player)
} | conditional_block |
game.rs | extern crate rustc_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable... | history: vec![],
}
}
pub fn turn_number(&self) -> usize {
self.history.len()
}
pub fn predict(&self, ai: Ai) -> Turn {
ai.next_move(self.turn_number(), &self.board)
}
fn check_winner(&self) -> Option<Player> {
self.check_road_winner().or(self.check_... | random_line_split | |
game.rs | extern crate rustc_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable... | (&mut self, turn: &str) -> Result<Option<Player>, String> {
let player = if self.history.len() % 2 == 0 {
Player::One
} else {
Player::Two
};
self.player_move(turn, player)
}
pub fn player_move(&mut self, turn: &str, player: Player) -> Result<Option<Playe... | play_simple | identifier_name |
client.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 futures::{Future, IntoFuture, Poll, Sink, StartSend, Stream};
use std::io::{Error, Result};
use std::net::Shutdow... |
pub fn new(inner: UnixStream) -> Self {
Authenticator { inner: inner.framed(AuthCodec) }
}
pub fn into_inner(self) -> UnixStream {
self.inner.into_inner()
}
pub fn into_bus(self) -> Bus {
Bus::new(self.into_inner())
}
pub fn prime(self) -> impl Future<Item = Self... | {
UnixStream::connect(path, handle)
.into_future()
.map(Self::new)
.and_then(Self::prime)
} | identifier_body |
client.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 futures::{Future, IntoFuture, Poll, Sink, StartSend, Stream};
use std::io::{Error, Result};
use std::net::Shutdow... | (&mut self, cmd: Self::Out, buf: &mut Vec<u8>) -> Result<()> {
commands::encode_client_cmd(&cmd, buf);
Ok(())
}
}
| encode | identifier_name |
client.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 futures::{Future, IntoFuture, Poll, Sink, StartSend, Stream};
use std::io::{Error, Result};
use std::net::Shutdow... |
pub fn into_inner(self) -> UnixStream {
self.inner.into_inner()
}
pub fn into_bus(self) -> Bus {
Bus::new(self.into_inner())
}
pub fn prime(self) -> impl Future<Item = Self, Error = Error> {
io::write_all(self.into_inner(), [0]).map(|(inner, _)| Authenticator::new(inner))
... | Authenticator { inner: inner.framed(AuthCodec) }
} | random_line_split |
seq.rs | use num::{One, Zero};
#[cfg(feature = "afserde")]
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::fmt;
use super::util::IndexableType;
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
#[repr(C... | (&self) -> T {
self.step
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "afserde")]
#[test]
fn seq_serde() {
use super::Seq;
use crate::seq;
// ANCHOR: seq_json_serde_snippet
let original = seq!(1:2:1);
let serd = match serde_json::to_string(&original) {
... | step | identifier_name |
seq.rs | use num::{One, Zero};
#[cfg(feature = "afserde")]
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::fmt;
use super::util::IndexableType;
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
#[repr(C... |
}
/// Enables use of `Seq` with `{}` format in print statements
impl<T> fmt::Display for Seq<T>
where
T: fmt::Display + IndexableType,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[begin: {}, end: {}, step: {}]",
self.begin, self.end, self.st... | {
Self {
begin: One::one(),
end: One::one(),
step: Zero::zero(),
}
} | identifier_body |
seq.rs | use num::{One, Zero};
#[cfg(feature = "afserde")]
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::fmt;
use super::util::IndexableType;
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
#[repr(C... | /// Get step size of Seq
pub fn step(&self) -> T {
self.step
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "afserde")]
#[test]
fn seq_serde() {
use super::Seq;
use crate::seq;
// ANCHOR: seq_json_serde_snippet
let original = seq!(1:2:1);
let serd ... | /// Get end index of Seq
pub fn end(&self) -> T {
self.end
}
| random_line_split |
transfer_encoding.rs | use header::Encoding;
header! {
#[doc="`Transfer-Encoding` header, defined in"]
#[doc="[RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.1)"]
#[doc=""] | #[doc="will be) applied to the payload body in order to form the message"]
#[doc="body."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Transfer-Encoding = 1#transfer-coding"]
#[doc="```"]
(TransferEncoding, "Transfer-Encoding") => (Encoding)+
}
bench_header!(normal, TransferEncodi... | #[doc="The `Transfer-Encoding` header field lists the transfer coding names"]
#[doc="corresponding to the sequence of transfer codings that have been (or"] | random_line_split |
borrowed-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
TheA { x: i64, y: i64 },
TheB (i64, i32, i32),
}
// This is a special case since it does not have the implicit discriminant field.
enum Univariant {
TheOnlyCase(i64)
}
fn main() {
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000... | ABC | identifier_name |
borrowed-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print *the_a_ref
// lldb-check:[...]$0 = TheA { x: 0, y: 8970181431921507452 }
// lldb-command:print *the_b_ref
// lldb-check:[...]$1 = TheB(0, 286331153, 286331153)
// lldb-comma... | // gdb-command:print *univariant_ref
// gdb-check:$3 = {{4820353753753434}} | random_line_split |
borrowed-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }
fn zzz() {()}
| {
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let the_a = TheA { x: 0, y: 8970181431921507452 };
let the_a_ref: &ABC = &the_a;
// 0b000100010... | identifier_body |
hstring.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,... | #[cfg(target_arch = "x86")]
UNION!{union HSTRING_HEADER_Reserved {
[u32; 5],
Reserved1 Reserved1_mut: PVOID,
Reserved2 Reserved2_mut: [c_char; 20],
}}
#[cfg(target_arch = "x86_64")]
UNION!{union HSTRING_HEADER_Reserved {
[u64; 3],
Reserved1 Reserved1_mut: PVOID,
Reserved2 Reserved2_mut: [c_char;... | //! This interface definition contains typedefs for Windows Runtime data types.
use ctypes::c_char;
use um::winnt::PVOID;
DECLARE_HANDLE!(HSTRING, HSTRING__); | random_line_split |
float_cmp.rs | #![warn(clippy::float_cmp)]
#![allow(
unused,
clippy::no_effect,
clippy::op_ref,
clippy::unnecessary_operation,
clippy::cast_lossless,
clippy::many_single_char_names
)]
use std::ops::Add;
const ZERO: f32 = 0.0;
const ONE: f32 = ZERO + 1.0;
fn twice<T>(x: T) -> T
where
T: Add<T, Output = T... | // no error, inside "eq" fn
}
fn fl_eq(x: f32, y: f32) -> bool {
if x.is_nan() { y.is_nan() } else { x == y } // no error, inside "eq" fn
}
struct X {
val: f32,
}
impl PartialEq for X {
fn eq(&self, o: &X) -> bool {
if self.val.is_nan() {
o.val.is_nan()
} else {
s... | { x == y } | conditional_block |
float_cmp.rs | #![warn(clippy::float_cmp)]
#![allow(
unused,
clippy::no_effect,
clippy::op_ref,
clippy::unnecessary_operation,
clippy::cast_lossless,
clippy::many_single_char_names
)]
use std::ops::Add;
const ZERO: f32 = 0.0;
const ONE: f32 = ZERO + 1.0;
fn twice<T>(x: T) -> T
where
T: Add<T, Output = T... | let x: f64 = 1.0;
x == 1.0;
x!= 0f64; // no error, comparison with zero is ok
twice(x)!= twice(ONE as f64);
x < 0.0; // no errors, lower or greater comparisons need no fuzzyness
x > 0.0;
x <= 0.0;
x >= 0.0;
let xs: [f32; 1] = [0.0];
let a: *const f32 = xs.as_ptr();
let b:... | ONE != 0.0; // no error, comparison with zero is ok
twice(ONE) != ONE;
ONE as f64 != 2.0;
ONE as f64 != 0.0; // no error, comparison with zero is ok
| random_line_split |
float_cmp.rs | #![warn(clippy::float_cmp)]
#![allow(
unused,
clippy::no_effect,
clippy::op_ref,
clippy::unnecessary_operation,
clippy::cast_lossless,
clippy::many_single_char_names
)]
use std::ops::Add;
const ZERO: f32 = 0.0;
const ONE: f32 = ZERO + 1.0;
fn twice<T>(x: T) -> T
where
T: Add<T, Output = T... | {
val: f32,
}
impl PartialEq for X {
fn eq(&self, o: &X) -> bool {
if self.val.is_nan() {
o.val.is_nan()
} else {
self.val == o.val // no error, inside "eq" fn
}
}
}
fn main() {
ZERO == 0f32; //no error, comparison with zero is ok
1.0f32!= f32::INFI... | X | identifier_name |
float_cmp.rs | #![warn(clippy::float_cmp)]
#![allow(
unused,
clippy::no_effect,
clippy::op_ref,
clippy::unnecessary_operation,
clippy::cast_lossless,
clippy::many_single_char_names
)]
use std::ops::Add;
const ZERO: f32 = 0.0;
const ONE: f32 = ZERO + 1.0;
fn twice<T>(x: T) -> T
where
T: Add<T, Output = T... |
struct X {
val: f32,
}
impl PartialEq for X {
fn eq(&self, o: &X) -> bool {
if self.val.is_nan() {
o.val.is_nan()
} else {
self.val == o.val // no error, inside "eq" fn
}
}
}
fn main() {
ZERO == 0f32; //no error, comparison with zero is ok
1.0f32!=... | {
if x.is_nan() { y.is_nan() } else { x == y } // no error, inside "eq" fn
} | identifier_body |
main.rs | #![feature(clamp)]
use std::{env, fs};
fn main() {
let uid = unsafe { geteuid() };
if uid!= 0 {
panic!("UID {} is not root", uid);
}
| }
}
fn run(cmd: &str) {
match cmd {
"+" => set(percent() + 10),
"-" => set(percent() - 10),
n if n.parse::<i64>().is_ok() => set(n.parse::<i64>().unwrap()),
_ => help(),
}
}
fn help() {
println!("brightness +|-|N");
}
fn max() -> i64 {
read("/sys/class/backlight/in... | let args: Vec<String> = env::args().collect();
match args.as_slice() {
[_, x] => run(x),
_ => help(), | random_line_split |
main.rs | #![feature(clamp)]
use std::{env, fs};
fn main() {
let uid = unsafe { geteuid() };
if uid!= 0 {
panic!("UID {} is not root", uid);
}
let args: Vec<String> = env::args().collect();
match args.as_slice() {
[_, x] => run(x),
_ => help(),
}
}
fn run(cmd: &str) {
match ... |
fn write(b: i64) {
fs::write(
"/sys/class/backlight/intel_backlight/brightness",
b.to_string(),
)
.unwrap();
}
#[link(name = "c")]
extern "C" {
fn geteuid() -> u32;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn t_test() {
assert_eq!(7500, max());
asse... | {
fs::read_to_string(path)
.unwrap_or_else(|_| panic!("Couldn't open file: {}", path))
.trim()
.parse::<i64>()
.unwrap_or_else(|e| panic!("Failed to read number from `{}`", e))
} | identifier_body |
main.rs | #![feature(clamp)]
use std::{env, fs};
fn main() {
let uid = unsafe { geteuid() };
if uid!= 0 {
panic!("UID {} is not root", uid);
}
let args: Vec<String> = env::args().collect();
match args.as_slice() {
[_, x] => run(x),
_ => help(),
}
}
fn run(cmd: &str) {
match ... | () {
write(5000)
}
}
| t_write | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
#![feature(never_type)]
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext... | (&self) {
// No-op by default.
}
}
/// Construct a heads fetcher (function that returns all the heads in the
/// repo) that uses the publishing bookmarks as all heads.
pub fn bookmark_heads_fetcher(
bookmarks: ArcBookmarks,
) -> Arc<dyn Fn(&CoreContext) -> BoxFuture<'static, Result<Vec<ChangesetId>>> +... | drop_caches | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
#![feature(never_type)]
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext... | {
Arc::new({
move |ctx: &CoreContext| {
bookmarks
.list(
ctx.clone(),
Freshness::MaybeStale,
&BookmarkPrefix::empty(),
BookmarkKind::ALL_PUBLISHING,
&BookmarkPagination::FromStart,... | identifier_body | |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
#![feature(never_type)]
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext... | bookmarks
.list(
ctx.clone(),
Freshness::MaybeStale,
&BookmarkPrefix::empty(),
BookmarkKind::ALL_PUBLISHING,
&BookmarkPagination::FromStart,
std::u64::MAX,
)... | Arc::new({
move |ctx: &CoreContext| { | random_line_split |
ratio.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Generic types for CSS values related to <ratio>.
//! https://drafts.csswg.org/css-values/#ratios
use std::fm... | <W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
self.0.to_css(dest)?;
// Even though 1 could be omitted, we don't per
// https://drafts.csswg.org/css-values-4/#ratio-value:
//
// The second <number> is optional, defaulting to 1. However,
... | to_css | identifier_name |
ratio.rs | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Generic types for CSS values related to <ratio>.
//! https://drafts.csswg.org/css-values/#ratios
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// A generic ... | /* This Source Code Form is subject to the terms of the Mozilla Public | random_line_split | |
issue-2935.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 ... |
trait it {
fn f(&self);
}
impl it for t {
fn f(&self) { }
}
pub fn main() {
// let x = ({a: 4i} as it);
// let y = @({a: 4i});
// let z = @({a: 4i} as it);
// let z = @({a: true} as it);
let z = @(@true as @it);
// x.f();
// y.f();
// (*z).f();
error!("ok so far...");
... | random_line_split | |
issue-2935.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 x = ({a: 4i} as it);
// let y = @({a: 4i});
// let z = @({a: 4i} as it);
// let z = @({a: true} as it);
let z = @(@true as @it);
// x.f();
// y.f();
// (*z).f();
error!("ok so far...");
z.f(); //segfault
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.