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 |
|---|---|---|---|---|
chip8.rs | extern crate sdl2;
use std::fs::File;
use std::io::prelude::*;
use std::time::{Duration, Instant};
#[cfg(feature="debugger")]
use std::process::Command;
use chip8::MEMORY_SIZE;
use chip8::ROM_START_ADDRESS;
use chip8::keyboard::Keyboard;
use chip8::display::Display;
#[cfg(feature="interpreter")]
use chip8::interpre... | (&self) {
println!("PC= {:x}", self.register_pc);
println!("I= {:x}", self.register_i);
println!("DT= {:x}", self.register_dt);
println!("ST= {:x}", self.register_st);
println!("SP= {:x}", self.register_sp);
for i in 0..16 as usize {
println!("V{}= {:x}", i, self.register_v[i]);
}
let _ = Command::ne... | print_registers | identifier_name |
chip8.rs | extern crate sdl2;
use std::fs::File;
use std::io::prelude::*;
use std::time::{Duration, Instant};
#[cfg(feature="debugger")]
use std::process::Command;
use chip8::MEMORY_SIZE;
use chip8::ROM_START_ADDRESS;
use chip8::keyboard::Keyboard;
use chip8::display::Display;
#[cfg(feature="interpreter")]
use chip8::interpre... |
}
pub fn run(&mut self, filename: String) {
self.load_rom(filename);
#[cfg(not(feature="interpreter"))]
let mut recompiler = Recompiler::new(&self.register_pc);
loop {
#[cfg(feature="debugger")]
self.print_registers();
#[cfg(feature="interpreter")]
Interpreter::execute_next_instruction(self... | {
self.time_last_frame = Instant::now();
self.keyboard.update_key_states();
self.display.refresh();
if self.register_dt > 0 {
self.register_dt -= 1
}
if self.register_st > 0 {
self.register_st -= 1;
// TODO: beep
}
} | conditional_block |
chip8.rs | extern crate sdl2;
use std::fs::File;
use std::io::prelude::*;
use std::time::{Duration, Instant};
#[cfg(feature="debugger")]
use std::process::Command;
use chip8::MEMORY_SIZE;
use chip8::ROM_START_ADDRESS;
use chip8::keyboard::Keyboard;
use chip8::display::Display;
#[cfg(feature="interpreter")]
use chip8::interpre... |
#[cfg(not(feature="interpreter"))]
recompiler.execute_next_code_block(self);
}
}
} | #[cfg(feature="interpreter")]
Interpreter::execute_next_instruction(self);
#[cfg(feature="interpreter")]
self.refresh(); | random_line_split |
parse.rs | use crate::{Error, Result};
use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree};
use quote::ToTokens;
use std::iter::Peekable;
pub(crate) fn parse_input(
input: TokenStream,
) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> {
let mut input = input.into_iter().peekable();
let mut attrs ... |
pub(crate) struct Attribute {
pub(crate) shebang: TokenTree,
pub(crate) group: TokenTree,
pub(crate) path: Option<Ident>,
}
impl Attribute {
pub(crate) fn path_is_ident(&self, ident: &str) -> bool {
self.path.as_ref().map_or(false, |p| *p == ident)
}
}
impl ToTokens for Attribute {
f... | {
let mut sig = Vec::new();
loop {
match input.peek() {
Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::Brace => {
return sig;
}
None => return sig,
_ => sig.push(input.next().unwrap()),
}
}
} | identifier_body |
parse.rs | use crate::{Error, Result};
use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree};
use quote::ToTokens;
use std::iter::Peekable;
pub(crate) fn parse_input(
input: TokenStream,
) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> {
let mut input = input.into_iter().peekable();
let mut attrs ... | shebang,
group: TokenTree::Group(group),
path,
}))
}
fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree> {
let mut sig = Vec::new();
loop {
match input.peek() {
Some(TokenTree::Group(ref group)) if group.delimiter() == Deli... |
Ok(Some(Attribute { | random_line_split |
parse.rs | use crate::{Error, Result};
use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree};
use quote::ToTokens;
use std::iter::Peekable;
pub(crate) fn parse_input(
input: TokenStream,
) -> Result<(Vec<Attribute>, Vec<TokenTree>, TokenTree)> {
let mut input = input.into_iter().peekable();
let mut attrs ... | (
input: &mut Peekable<impl Iterator<Item = TokenTree>>,
) -> Result<Option<Attribute>> {
let shebang = match input.peek() {
Some(TokenTree::Punct(ref punct)) if punct.as_char() == '#' => input.next().unwrap(),
_ => return Ok(None),
};
let group = match input.peek() {
Some(Token... | parse_next_attr | identifier_name |
browsing_context.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/. */
//! Liberally derived from the [Firefox JS implementation]
//! (http://mxr.mozilla.org/mozilla-central/source/tool... | {
pub name: String,
pub title: String,
pub url: String,
pub console: String,
pub emulation: String,
pub inspector: String,
pub timeline: String,
pub profiler: String,
pub performance: String,
pub styleSheets: String,
pub thread: String,
}
impl Actor for BrowsingContextActor... | BrowsingContextActor | identifier_name |
browsing_context.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/. */
//! Liberally derived from the [Firefox JS implementation]
//! (http://mxr.mozilla.org/mozilla-central/source/tool... | consoleActor: String,
emulationActor: String,
inspectorActor: String,
timelineActor: String,
profilerActor: String,
performanceActor: String,
styleSheetsActor: String,
}
pub struct BrowsingContextActor {
pub name: String,
pub title: String,
pub url: String,
pub console: Stri... | actor: String,
title: String,
url: String,
outerWindowID: u32, | random_line_split |
mirror.rs | // Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | desc: NSArray<MTLVertexAttribute>) {
use map::{map_base_type, map_container_type};
for idx in 0..desc.count() {
let attr = desc.object_at(idx);
info.vertex_attributes.push(shade::AttributeVar {
name: attr.name().into(),
slot: attr.attri... | random_line_split | |
mirror.rs | // Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | (info: &mut shade::ProgramInfo,
desc: NSArray<MTLVertexAttribute>) {
use map::{map_base_type, map_container_type};
for idx in 0..desc.count() {
let attr = desc.object_at(idx);
info.vertex_attributes.push(shade::AttributeVar {
name: attr.name().into... | populate_vertex_attributes | identifier_name |
mirror.rs | // Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
pub fn populate_info(info: &mut shade::ProgramInfo,
stage: shade::Stage,
args: NSArray<MTLArgument>) {
use map::{map_base_type, map_texture_type};
let usage = stage.into();
for idx in 0..args.count() {
let arg = args.object_at(idx);
let name = ar... | {
use map::{map_base_type, map_container_type};
for idx in 0..desc.count() {
let attr = desc.object_at(idx);
info.vertex_attributes.push(shade::AttributeVar {
name: attr.name().into(),
slot: attr.attribute_index() as core::AttributeSlot,
base_type: map_base_... | identifier_body |
mirror.rs | // Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
info.constant_buffers.push(shade::ConstantBufferVar {
name: name.into(),
slot: arg.index() as core::ConstantBufferSlot,
size: arg.buffer_data_size() as usize,
usage: usage,
elements: Vec::new(), // TODO... | {
continue;
} | conditional_block |
leaky_bucket.rs | extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;
use ratelimit_meter::{
algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket,
NegativeMultiDecision, NonConformance,
};
use std::thread;
use std::time::Duration;
#[test]
fn accepts_first_cell() {
let mut l... | () {
let mut lim = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(20u32));
let now = current_moment();
let ms = Duration::from_millis(1);
let mut children = vec![];
lim.check_at(now).unwrap();
for _i in 0..20 {
let mut lim = lim.clone();
children.push(thread::spawn(move |... | actual_threadsafety | identifier_name |
leaky_bucket.rs | extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;
use ratelimit_meter::{
algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket,
NegativeMultiDecision, NonConformance,
};
use std::thread;
use std::time::Duration;
#[test]
fn accepts_first_cell() {
let mut l... |
#[test]
fn never_allows_more_than_capacity() {
let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32));
let now = current_moment();
let ms = Duration::from_millis(1);
// Should not allow the first 15 cells on a capacity 5 bucket:
assert_ne!(Ok(()), lb.check_n_at(15, now));
... | {
let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(2u32));
let now = current_moment();
let ms = Duration::from_millis(1);
assert_eq!(Ok(()), lb.check_at(now));
assert_eq!(Ok(()), lb.check_at(now));
assert_ne!(Ok(()), lb.check_at(now + ms * 2));
// should be ok again in 1s... | identifier_body |
leaky_bucket.rs | extern crate ratelimit_meter;
#[macro_use]
extern crate nonzero_ext;
use ratelimit_meter::{
algorithms::Algorithm, test_utilities::current_moment, DirectRateLimiter, LeakyBucket,
NegativeMultiDecision, NonConformance,
};
use std::thread;
use std::time::Duration;
#[test]
fn accepts_first_cell() {
let mut l... | let mut lb = DirectRateLimiter::<LeakyBucket>::per_second(nonzero!(5u32));
let now = current_moment();
let ms = Duration::from_millis(1);
// Should not allow the first 15 cells on a capacity 5 bucket:
assert_ne!(Ok(()), lb.check_n_at(15, now));
// After 3 and 20 seconds, it should not allow 15... | }
#[test]
fn never_allows_more_than_capacity() { | random_line_split |
map-types.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: Box<HashMap<int, int>> = box HashMap::new();
let x: Box<Map<int, int>> = x;
let y: Box<Map<uint, int>> = box x;
//~^ ERROR the trait `collections::Map<uint,int>` is not implemented
}
| main | identifier_name |
map-types.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: Box<HashMap<int, int>> = box HashMap::new();
let x: Box<Map<int, int>> = x;
let y: Box<Map<uint, int>> = box x;
//~^ ERROR the trait `collections::Map<uint,int>` is not implemented
} | identifier_body | |
map-types.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 ... |
fn main() {
let x: Box<HashMap<int, int>> = box HashMap::new();
let x: Box<Map<int, int>> = x;
let y: Box<Map<uint, int>> = box x;
//~^ ERROR the trait `collections::Map<uint,int>` is not implemented
} |
use std::collections::HashMap;
// Test that trait types printed in error msgs include the type arguments. | random_line_split |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if!valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if!valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let s... | else {
sum.push(r);
next_r = digits_r.next();
}
},
(Some(l), None) => {
sum.push(l);
next_l = digits_l.next();
},
(None, Some(r)) => {
sum.push(r);
nex... | {
sum.push(l);
next_l = digits_l.next();
} | conditional_block |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if!valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if!valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let s... | assert_eq!("LI", add("L", "I").unwrap());
}
#[test]
fn add_l_xi_understands_l_x_sort_order() {
assert_eq!("LXI", add("L", "XI").unwrap());
}
#[test]
fn add_fails_when_result_is_too_big_to_be_represented() {
assert!(add("MCMXCIX", "MMCMXCIX").is_err());
}
#[test... | fn add_l_i_supports_l() { | random_line_split |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if!valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if!valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let s... |
#[test]
fn add_l_xi_understands_l_x_sort_order() {
assert_eq!("LXI", add("L", "XI").unwrap());
}
#[test]
fn add_fails_when_result_is_too_big_to_be_represented() {
assert!(add("MCMXCIX", "MMCMXCIX").is_err());
}
#[test]
fn add_fails_when_lhs_is_invalid() {
asse... | {
assert_eq!("LI", add("L", "I").unwrap());
} | identifier_body |
add.rs | use std::cmp::Ordering;
use cmp;
use denormalize;
use normalize;
use valid;
pub fn add(num_l: &str, num_r: &str) -> Result<String, String> {
if!valid(num_l) {
Err(format!("Invalid numeral {}", num_l))
} else if!valid(num_r) {
Err(format!("Invalid numeral {}", num_r))
} else {
let s... | () {
assert_eq!("LXI", add("L", "XI").unwrap());
}
#[test]
fn add_fails_when_result_is_too_big_to_be_represented() {
assert!(add("MCMXCIX", "MMCMXCIX").is_err());
}
#[test]
fn add_fails_when_lhs_is_invalid() {
assert!(add("J", "I").is_err());
}
#[test]
fn a... | add_l_xi_understands_l_x_sort_order | identifier_name |
bounds.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 ... | (cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: |P<Item>|) {
let name = match mitem.node {
MetaWord(ref tname) => {
match tname.get() {
"Copy" ... | expand_deriving_bound | identifier_name |
bounds.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 ... | ,
_ => {
return cx.span_err(span, "unexpected value in deriving, expected \
a trait")
}
};
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "kinds", name)),
additional_bou... | {
match tname.get() {
"Copy" => "Copy",
"Send" => "Send",
"Sync" => "Sync",
ref tname => {
cx.span_bug(span,
format!("expected built-in trait name but \
... | conditional_block |
bounds.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 trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "kinds", name)),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!()
};
trait_def.expand(cx, mitem, item, push)
}
| {
let name = match mitem.node {
MetaWord(ref tname) => {
match tname.get() {
"Copy" => "Copy",
"Send" => "Send",
"Sync" => "Sync",
ref tname => {
cx.span_bug(span,
format!("expect... | identifier_body |
bounds.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 ... | }
}
},
_ => {
return cx.span_err(span, "unexpected value in deriving, expected \
a trait")
}
};
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std"... | cx.span_bug(span,
format!("expected built-in trait name but \
found {}",
*tname).as_slice()) | random_line_split |
login.rs | use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct | {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const USAGE: &'static str = "
Save an api token from the registry locally
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token... | Options | identifier_name |
login.rs | use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CliResult, CliError, Config};
#[derive(RustcDecodable)]
struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: bool,
}
pub const U... | cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token for
-v, --verbose Use verbose output
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
config.shell().set_verbose(options.flag_... |
Usage: | random_line_split |
text_expression_methods.rs | use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};
/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
/// C... |
/// Returns a SQL `NOT LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On PostgreSQL `NOT LIKE` is case sensitive. You may use
/// [`not_ilike()`](../expression_methods/trait.PgTextExpressionMethods.html#method.not_ilike)
/// for case insensitive comparison o... | {
Grouped(Like::new(self, other.as_expression()))
} | identifier_body |
text_expression_methods.rs | use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};
/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
/// C... | /// #
/// # insert_into(users)
/// # .values(&vec![
/// # (id.eq(1), name.eq("Sean"), hair_color.eq(Some("Green"))),
/// # (id.eq(2), name.eq("Tess"), hair_color.eq(None)),
/// # ])
/// # .execute(&connection)
/// # .unwrap();
... | /// # )").unwrap(); | random_line_split |
text_expression_methods.rs | use crate::dsl;
use crate::expression::grouped::Grouped;
use crate::expression::operators::{Concat, Like, NotLike};
use crate::expression::{AsExpression, Expression};
use crate::sql_types::{Nullable, SqlType, Text};
/// Methods present on text expressions
pub trait TextExpressionMethods: Expression + Sized {
/// C... | <T>(self, other: T) -> dsl::Like<Self, T>
where
Self::SqlType: SqlType,
T: AsExpression<Self::SqlType>,
{
Grouped(Like::new(self, other.as_expression()))
}
/// Returns a SQL `NOT LIKE` expression
///
/// This method is case insensitive for SQLite and MySQL.
/// On Po... | like | identifier_name |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, Con... | File::open(path).map_err(|e| format!("Failed to send file '{:?}': {}",
path, e))
});
let mut stream = try!(self.start());
match copy(&mut file, &mut stream) {
Ok(_) => Ok(Halt(stream)),
Err(e) => stream.bail(fo... | let mut file = try_with!(self, { | random_line_split |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, Con... | <'a, T:'static + Any = Fresh> {
///the original `hyper::server::Response`
origin: HyperResponse<'a, T>,
templates: &'a TemplateCache
}
impl<'a> Response<'a, Fresh> {
pub fn from_internal<'c, 'd>(response: HyperResponse<'c, Fresh>,
templates: &'c TemplateCache)
... | Response | identifier_name |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, Con... |
}
impl <'a, T:'static + Any> Response<'a, T> {
/// The status of this response.
pub fn status(&self) -> StatusCode {
self.origin.status()
}
/// The headers of this response.
pub fn headers(&self) -> &Headers {
self.origin.headers()
}
}
fn mime_from_filename<P: AsRef<Path>>(pa... | {
self.origin.end()
} | identifier_body |
response.rs | use std::borrow::Cow;
use std::sync::RwLock;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::path::Path;
use serialize::Encodable;
use hyper::status::StatusCode;
use hyper::server::Response as HyperResponse;
use hyper::header::{
Headers, Date, HttpDate, Server, Con... |
}
/// Renders the given template bound with the given data.
///
/// # Examples
/// ```{rust}
/// use std::collections::HashMap;
/// use nickel::{Request, Response, MiddlewareResult};
///
/// # #[allow(dead_code)]
/// fn handler<'a>(_: &mut Request, res: Response<'a>) -> Middlew... | { headers.set(f()) } | conditional_block |
typeclasses-eq-example-static.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 ... | {
leaf(Color),
branch(@ColorTree, @ColorTree)
}
impl Equal for ColorTree {
fn isEq(a: ColorTree, b: ColorTree) -> bool {
match (a, b) {
(leaf(x), leaf(y)) => { Equal::isEq(x, y) }
(branch(l1, r1), branch(l2, r2)) => {
Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2)
... | ColorTree | identifier_name |
typeclasses-eq-example-static.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 ... | branch(@ColorTree, @ColorTree)
}
impl Equal for ColorTree {
fn isEq(a: ColorTree, b: ColorTree) -> bool {
match (a, b) {
(leaf(x), leaf(y)) => { Equal::isEq(x, y) }
(branch(l1, r1), branch(l2, r2)) => {
Equal::isEq(*l1, *l2) && Equal::isEq(*r1, *r2)
}
... | enum ColorTree {
leaf(Color), | random_line_split |
typeclasses-eq-example-static.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 ... |
(yellow, yellow) => { true }
(black, black) => { true }
_ => { false }
}
}
}
enum ColorTree {
leaf(Color),
branch(@ColorTree, @ColorTree)
}
impl Equal for ColorTree {
fn isEq(a: ColorTree, b: ColorTree) -> bool {
match (a, b) {
... | { true } | conditional_block |
backend.rs | use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite};
use crate::fair_queue::QueueInner;
use crate::util::PeerIdentity;
use crate::{
MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult,
};
use async_trait::async_trait;
use crossbeam::queue::SegQueue;
use dash... | self.peer_disconnected(&next_peer_id);
Err(e.into())
}
};
}
}
}
impl SocketBackend for GenericSocketBackend {
fn socket_type(&self) -> SocketType {
self.socket_type
}
fn socket_options(&self) -> &SocketOptions {
... | }
Err(e) => { | random_line_split |
backend.rs | use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite};
use crate::fair_queue::QueueInner;
use crate::util::PeerIdentity;
use crate::{
MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult,
};
use async_trait::async_trait;
use crossbeam::queue::SegQueue;
use dash... | (&self, peer_id: &PeerIdentity) {
self.peers.remove(peer_id);
match &self.fair_queue_inner {
None => {}
Some(inner) => {
inner.lock().remove(peer_id);
}
};
}
}
| peer_disconnected | identifier_name |
backend.rs | use crate::codec::{FramedIo, Message, ZmqFramedRead, ZmqFramedWrite};
use crate::fair_queue::QueueInner;
use crate::util::PeerIdentity;
use crate::{
MultiPeerBackend, SocketBackend, SocketEvent, SocketOptions, SocketType, ZmqError, ZmqResult,
};
use async_trait::async_trait;
use crossbeam::queue::SegQueue;
use dash... |
}
#[async_trait]
impl MultiPeerBackend for GenericSocketBackend {
async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo) {
let (recv_queue, send_queue) = io.into_parts();
self.peers.insert(peer_id.clone(), Peer { send_queue });
self.round_robin.push(peer_id.clone())... | {
&self.socket_monitor
} | identifier_body |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
us... |
}
}
pub fn add_from_string(&self, string: &str) -> Result<(), Error> {
unsafe {
let mut error = ::std::ptr::null_mut();
ffi::gtk_builder_add_from_string(self.to_glib_none().0,
string.as_ptr() as *const c_char,
... | { Err(from_glib_full(error)) } | conditional_block |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
us... |
#[cfg(feature = "v3_10")]
pub fn new_from_file<T: AsRef<Path>>(file_path: T) -> Builder {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new_from_file(file_path.as_ref().to_glib_none().0)) }
}
#[cfg(feature = "v3_10")]
pub fn new_from_resource(resource... | {
assert_initialized_main_thread!();
unsafe { from_glib_full(ffi::gtk_builder_new()) }
} | identifier_body |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
us... | <T: IsA<Object>>(&self, name: &str) -> Option<T> {
unsafe {
Option::<Object>::from_glib_none(
ffi::gtk_builder_get_object(self.to_glib_none().0, name.to_glib_none().0))
.and_then(|obj| obj.downcast().ok())
}
}
pub fn add_from_file<T: AsRef<Path>>(&self... | get_object | identifier_name |
builder.rs | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
#![cfg_attr(not(feature = "v3_10"), allow(unused_imports))]
use libc::{c_char, ssize_t};
us... | from_glib_full(
ffi::gtk_builder_new_from_string(string.as_ptr() as *const c_char,
string.len() as ssize_t))
}
}
pub fn get_object<T: IsA<Object>>(&self, name: &str) -> Option<T> {
unsafe {
Option::<Object>::from_glib_none(
... | #[cfg(feature = "v3_10")]
pub fn new_from_string(string: &str) -> Builder {
assert_initialized_main_thread!();
unsafe {
// Don't need a null-terminated string here | random_line_split |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it wi... | println!("Domain info:");
println!(" State: {}", dinfo.state);
println!(" Max Memory: {}", dinfo.max_mem);
println!(" Memory: {}", dinfo.memory);
println!(" CPUs: {}", dinfo.nr_virt_cpu);
... | {
let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE |
virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE;
if let Ok(num_active_domains) = conn.num_of_domains() {
if let Ok(num_inactive_domains) = conn.num_of_defined_domains() {
println!("There are {} active and {} ina... | identifier_body |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it wi... | (conn: &Connect) -> Result<(), Error> {
let flags = virt::connect::VIR_CONNECT_LIST_DOMAINS_ACTIVE |
virt::connect::VIR_CONNECT_LIST_DOMAINS_INACTIVE;
if let Ok(num_active_domains) = conn.num_of_domains() {
if let Ok(num_inactive_domains) = conn.num_of_defined_domains() {
pr... | show_domains | identifier_name |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it wi... | return Ok(());
}
}
Err(Error::new())
}
fn main() {
let uri = match env::args().nth(1) {
Some(u) => u,
None => String::from(""),
};
println!("Attempting to connect to hypervisor: '{}'", uri);
let conn = match Connect::open(&uri) {
Ok(c) => c,
... | }
}
} | random_line_split |
hello.rs | /*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it wi... |
if let Err(e) = show_domains(&conn) {
disconnect(conn);
panic!("Failed to show domains info: code {}, message: {}",
e.code,
e.message);
}
fn disconnect(mut conn: Connect) {
if let Err(e) = conn.close() {
panic!("Failed to disconnect from h... | {
disconnect(conn);
panic!("Failed to show hypervisor info: code {}, message: {}",
e.code,
e.message);
} | conditional_block |
kay_auto.rs | //! This is all auto-generated. Do not touch.
#![rustfmt::skip]
#[allow(unused_imports)]
use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait};
#[allow(unused_imports)]
use super::*;
#[derive(Serialize, Deserialize)] #[serde(transparent)]
pub struct TimeUIID {
_raw_id: RawID
}
impl C... |
pub fn register_trait(system: &mut ActorSystem) {
system.register_trait::<TimeUIRepresentative>();
system.register_trait_message::<MSG_TimeUI_on_time_info>();
}
pub fn register_implementor<Act: Actor + TimeUI>(system: &mut ActorSystem) {
system.register_implementor::<Act, TimeUIRe... | {
world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed));
} | identifier_body |
kay_auto.rs | //! This is all auto-generated. Do not touch.
#![rustfmt::skip]
#[allow(unused_imports)]
use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait};
#[allow(unused_imports)]
use super::*;
#[derive(Serialize, Deserialize)] #[serde(transparent)]
pub struct TimeUIID {
_raw_id: RawID
}
impl C... | (self, current_instant: :: units :: Instant, speed: u16, world: &mut World) {
world.send(self.as_raw(), MSG_TimeUI_on_time_info(current_instant, speed));
}
pub fn register_trait(system: &mut ActorSystem) {
system.register_trait::<TimeUIRepresentative>();
system.register_trait_message::<... | on_time_info | identifier_name |
kay_auto.rs | //! This is all auto-generated. Do not touch.
#![rustfmt::skip]
#[allow(unused_imports)]
use kay::{ActorSystem, TypedID, RawID, Fate, Actor, TraitIDFrom, ActorOrActorTrait};
#[allow(unused_imports)]
use super::*;
#[derive(Serialize, Deserialize)] #[serde(transparent)]
pub struct TimeUIID {
_raw_id: RawID
}
| }
}
impl ::std::hash::Hash for TimeUIID {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self._raw_id.hash(state);
}
}
impl PartialEq for TimeUIID {
fn eq(&self, other: &TimeUIID) -> bool {
self._raw_id == other._raw_id
}
}
impl Eq for TimeUIID {}
pub struct TimeUIRepresent... | impl Copy for TimeUIID {}
impl Clone for TimeUIID { fn clone(&self) -> Self { *self } }
impl ::std::fmt::Debug for TimeUIID {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "TimeUIID({:?})", self._raw_id) | random_line_split |
mod.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | pub use self::schedule::{Schedule, CleanDustMode};
pub use types::executed::CallType; | pub use self::factory::Factory; | random_line_split |
parity_signing.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | use jsonrpc_core::Error;
use futures::BoxFuture;
use v1::types::{U256, H160, Bytes, ConfirmationResponse, TransactionRequest, Either};
build_rpc_trait! {
/// Signing methods implementation.
pub trait ParitySigning {
type Metadata;
/// Posts sign request asynchronously.
/// Will return a confirmation ID for l... | //! ParitySigning rpc interface. | random_line_split |
u_char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#[stable]
fn is_lowercase(self) -> bool {
match self {
'a'... 'z' => true,
c if c > '\x7f' => derived_property::Lowercase(c),
_ => false
}
}
#[stable]
fn is_uppercase(self) -> bool {
match self {
'A'... 'Z' => true,
... | { derived_property::XID_Continue(self) } | identifier_body |
u_char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (self) -> bool {
match self {
'a'... 'z' | 'A'... 'Z' => true,
c if c > '\x7f' => derived_property::Alphabetic(c),
_ => false
}
}
#[unstable = "mainly needed for compiler internals"]
fn is_xid_start(self) -> bool { derived_property::XID_Start(self) }
... | is_alphabetic | identifier_name |
u_char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | #[stable]
fn len_utf8(self) -> uint;
/// Returns the amount of bytes this character would need if encoded in
/// UTF-16.
#[stable]
fn len_utf16(self) -> uint;
/// Encodes this character as UTF-8 into the provided byte buffer,
/// and then returns the number of bytes written.
///
... | /// Returns the amount of bytes this character would need if encoded in
/// UTF-8. | random_line_split |
lib.rs | #![feature(globs)]
use std::collections::HashMap;
use std::fmt::{Show, FormatError, Formatter};
use std::os;
use std::str;
pub use self::gnu::GnuMakefile;
// XXX: no idea why this is necessary
#[path = "gnu/mod.rs"]
pub mod gnu;
pub type TokenResult<T> = Result<T, TokenError>;
pub type ParseResult<T> = Result<T, Pa... | <'a> {
rules: HashMap<&'a [u8], MakefileRule<'a>>,
funcs: HashMap<&'a [u8], &'a [u8]>
}
pub struct MakefileRule<'a> {
name: &'a [u8],
deps: Vec<&'a MakefileRule<'a>>,
body: &'a [u8]
}
pub struct ParseError {
pub message: String,
pub code: int
}
pub struct TokenError {
pub message: String,
... | MakefileDag | identifier_name |
lib.rs | #![feature(globs)]
use std::collections::HashMap;
use std::fmt::{Show, FormatError, Formatter};
use std::os;
use std::str;
pub use self::gnu::GnuMakefile;
// XXX: no idea why this is necessary
#[path = "gnu/mod.rs"]
pub mod gnu;
pub type TokenResult<T> = Result<T, TokenError>;
pub type ParseResult<T> = Result<T, Pa... | }
impl<'a> MakefileRule<'a> {
#[inline]
pub fn new(name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8]) -> MakefileRule<'a> {
MakefileRule {
name: name,
deps: deps,
body: body
}
}
}
impl ParseError {
#[inline]
pub fn new(msg: String, code: int) -> Pars... | } | random_line_split |
context.rs | use get_error;
use rwops::RWops;
use std::error;
use std::fmt;
use std::io;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use sys::ttf;
use version::Version;
use super::font::{
internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font,
};
/// A context manager for `SDL2_TTF` to m... | }
}
}
impl Sdl2TtfContext {
/// Loads a font from the given file with the given size in points.
pub fn load_font<'ttf, P: AsRef<Path>>(
&'ttf self,
path: P,
point_size: u16,
) -> Result<Font<'ttf,'static>, String> {
internal_load_font(path, point_size)
}
... | unsafe {
ttf::TTF_Quit(); | random_line_split |
context.rs | use get_error;
use rwops::RWops;
use std::error;
use std::fmt;
use std::io;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use sys::ttf;
use version::Version;
use super::font::{
internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font,
};
/// A context manager for `SDL2_TTF` to m... |
/// Loads the font at the given index of the file, with the given
/// size in points.
pub fn load_font_at_index<'ttf, P: AsRef<Path>>(
&'ttf self,
path: P,
index: u32,
point_size: u16,
) -> Result<Font<'ttf,'static>, String> {
internal_load_font_at_index(path, i... | {
internal_load_font(path, point_size)
} | identifier_body |
context.rs | use get_error;
use rwops::RWops;
use std::error;
use std::fmt;
use std::io;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use sys::ttf;
use version::Version;
use super::font::{
internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font,
};
/// A context manager for `SDL2_TTF` to m... | else {
Ok(internal_load_font_from_ll(raw, Some(rwops)))
}
}
}
/// Returns the version of the dynamically linked `SDL_TTF` library
pub fn get_linked_version() -> Version {
unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) }
}
/// An error for when `sdl2_ttf` is attempted initialized tw... | {
Err(get_error())
} | conditional_block |
context.rs | use get_error;
use rwops::RWops;
use std::error;
use std::fmt;
use std::io;
use std::os::raw::{c_int, c_long};
use std::path::Path;
use sys::ttf;
use version::Version;
use super::font::{
internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font,
};
/// A context manager for `SDL2_TTF` to m... | (&self) -> &str {
match *self {
InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized",
InitError::InitializationError(ref error) => error.description(),
}
}
fn cause(&self) -> Option<&dyn error::Error> {
match *self {
InitError... | description | identifier_name |
sched.rs | //! Execution scheduling
//!
//! See Also
//! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html)
use crate::{Errno, Result};
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use self::sched_linux_like::*;
#[cfg(any(target_os = "android", target_os = "linux"))]
mod sched_linux... |
/// Add a CPU to CpuSet.
/// `field` is the CPU id to add
pub fn set(&mut self, field: usize) -> Result<()> {
if field >= CpuSet::count() {
Err(Errno::EINVAL)
} else {
unsafe { libc::CPU_SET(field, &mut self.cpu_set); }
Ok... | {
if field >= CpuSet::count() {
Err(Errno::EINVAL)
} else {
Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) })
}
} | identifier_body |
sched.rs | //! Execution scheduling
//!
//! See Also
//! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html)
use crate::{Errno, Result};
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use self::sched_linux_like::*;
#[cfg(any(target_os = "android", target_os = "linux"))]
mod sched_linux... |
}
/// Remove a CPU from CpuSet.
/// `field` is the CPU id to remove
pub fn unset(&mut self, field: usize) -> Result<()> {
if field >= CpuSet::count() {
Err(Errno::EINVAL)
} else {
unsafe { libc::CPU_CLR(field, &mut self.cpu_set);}... | {
unsafe { libc::CPU_SET(field, &mut self.cpu_set); }
Ok(())
} | conditional_block |
sched.rs | //! Execution scheduling
//!
//! See Also
//! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html)
use crate::{Errno, Result};
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use self::sched_linux_like::*;
#[cfg(any(target_os = "android", target_os = "linux"))]
mod sched_linux... | {
cpu_set: libc::cpu_set_t,
}
impl CpuSet {
/// Create a new and empty CpuSet.
pub fn new() -> CpuSet {
CpuSet {
cpu_set: unsafe { mem::zeroed() },
}
}
/// Test to see if a CPU is in the CpuSet.
/// `field` is the CPU id ... | CpuSet | identifier_name |
rawlink.rs | // This file is part of Intrusive.
// Intrusive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Intrusive is distributed... |
/// Convert the `Rawlink` into an Option value
pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> {
if self.p.is_null() {
None
} else {
Some(unsafe { mem::transmute(self.p) })
}
}
/// Return the `Rawlink` and replace with `Rawlink::none()`
pub f... | {
unsafe {
mem::transmute(self.p.as_ref())
}
} | identifier_body |
rawlink.rs | // This file is part of Intrusive.
// Intrusive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Intrusive is distributed... | None
} else {
Some(unsafe { mem::transmute(self.p) })
}
}
/// Return the `Rawlink` and replace with `Rawlink::none()`
pub fn take(&mut self) -> Rawlink<T> {
mem::replace(self, Rawlink::none())
}
}
impl<T> PartialEq for Rawlink<T> {
#[inline]
fn e... | random_line_split | |
rawlink.rs | // This file is part of Intrusive.
// Intrusive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Intrusive is distributed... | () -> Rawlink<T> { Rawlink::none() }
}
| default | identifier_name |
rawlink.rs | // This file is part of Intrusive.
// Intrusive is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Intrusive is distributed... |
}
/// Return the `Rawlink` and replace with `Rawlink::none()`
pub fn take(&mut self) -> Rawlink<T> {
mem::replace(self, Rawlink::none())
}
}
impl<T> PartialEq for Rawlink<T> {
#[inline]
fn eq(&self, other: &Rawlink<T>) -> bool {
self.p == other.p
}
}
impl<T> Clone for Raw... | {
Some(unsafe { mem::transmute(self.p) })
} | conditional_block |
match-vec-rvalue.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 ... | () {
match vec!(1, 2, 3) {
x => {
assert_eq!(x.len(), 3);
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
}
}
}
| main | identifier_name |
match-vec-rvalue.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 ... |
}
}
| {
assert_eq!(x.len(), 3);
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
} | conditional_block |
match-vec-rvalue.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 ... | {
match vec!(1, 2, 3) {
x => {
assert_eq!(x.len(), 3);
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
}
}
} | identifier_body | |
match-vec-rvalue.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 ... | assert_eq!(x[2], 3);
}
}
} | assert_eq!(x[0], 1);
assert_eq!(x[1], 2); | random_line_split |
whoami.rs | use irc::{IrcMsg, server};
use command_mapper::{
RustBotPlugin,
CommandMapperDispatch,
IrcBotConfigurator,
Format,
Token,
};
const CMD_WHOAMI: Token = Token(0);
const CMD_WHEREAMI: Token = Token(1);
pub struct WhoAmIPlugin;
impl WhoAmIPlugin {
pub fn new() -> WhoAmIPlugin {
WhoAmIPl... |
impl RustBotPlugin for WhoAmIPlugin {
fn configure(&mut self, conf: &mut IrcBotConfigurator) {
conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap());
conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap());
}
fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, m... | {
match m.command().token {
CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI),
CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI),
_ => None
}
} | identifier_body |
whoami.rs | use irc::{IrcMsg, server};
use command_mapper::{
RustBotPlugin,
CommandMapperDispatch,
IrcBotConfigurator,
Format,
Token,
};
const CMD_WHOAMI: Token = Token(0);
const CMD_WHEREAMI: Token = Token(1);
pub struct WhoAmIPlugin;
impl WhoAmIPlugin {
pub fn new() -> WhoAmIPlugin {
WhoAmIPl... | () -> &'static str {
"whoami"
}
}
enum WhoAmICommandType {
WhoAmI,
WhereAmI
}
fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> {
match m.command().token {
CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI),
CMD_WHEREAMI => Some(WhoAmICommandType::WhereAm... | get_plugin_name | identifier_name |
whoami.rs | use irc::{IrcMsg, server};
use command_mapper::{
RustBotPlugin,
CommandMapperDispatch,
IrcBotConfigurator,
Format,
Token,
};
const CMD_WHOAMI: Token = Token(0);
const CMD_WHEREAMI: Token = Token(1);
| WhoAmIPlugin
}
pub fn get_plugin_name() -> &'static str {
"whoami"
}
}
enum WhoAmICommandType {
WhoAmI,
WhereAmI
}
fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> {
match m.command().token {
CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI),
... | pub struct WhoAmIPlugin;
impl WhoAmIPlugin {
pub fn new() -> WhoAmIPlugin { | random_line_split |
whoami.rs | use irc::{IrcMsg, server};
use command_mapper::{
RustBotPlugin,
CommandMapperDispatch,
IrcBotConfigurator,
Format,
Token,
};
const CMD_WHOAMI: Token = Token(0);
const CMD_WHEREAMI: Token = Token(1);
pub struct WhoAmIPlugin;
impl WhoAmIPlugin {
pub fn new() -> WhoAmIPlugin {
WhoAmIPl... | ,
None => ()
}
}
} | {
m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target));
} | conditional_block |
advent9.rs | // advent9.rs
//
// Traveling Santa Problem
extern crate permutohedron;
#[macro_use] extern crate scan_fmt;
use std::io;
fn main() {
let mut city_table = CityDistances::new();
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
... | (&mut self, city: &str) -> usize {
match self.cities.iter().position(|x| x == city) {
Some(idx) => idx,
None => {
self.cities.push(String::from(city));
self.cities.len() - 1
}
}
}
fn add_distance(&mut self, city1: &str, city2: ... | find_city_idx | identifier_name |
advent9.rs | // advent9.rs
//
// Traveling Santa Problem
extern crate permutohedron;
#[macro_use] extern crate scan_fmt;
use std::io;
fn main() {
let mut city_table = CityDistances::new();
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
... |
#[test]
fn test_distance_struct() {
let mut cities = CityDistances::new();
cities.add_distance("Hoth", "Tatooine", 1000);
cities.add_distance("Hoth", "Coruscant", 300);
cities.add_distance("Coruscant", "Tatooine", 900);
assert_eq!(1000, cities.find_distance(0, 1));
assert_eq!(1000, cities.find... | {
let mut indices: Vec<_> = (0..city_table.cities.len()).collect();
permutohedron::Heap::new(&mut indices[..])
.map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1])))
.min().unwrap()
} | identifier_body |
advent9.rs | // advent9.rs
//
// Traveling Santa Problem
extern crate permutohedron;
#[macro_use] extern crate scan_fmt;
use std::io;
fn main() {
let mut city_table = CityDistances::new();
loop { | match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
// Parse input
let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String... | let mut input = String::new();
let result = io::stdin().read_line(&mut input); | random_line_split |
mutex.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub unsafe fn destroy(&self) {
let lock = self.lock.get();
let recursion = self.recursion.get();
assert_eq!(
(*lock).load(Ordering::Relaxed),
abi::LOCK_UNLOCKED.0,
"Attempted to destroy locked mutex"
);
assert_eq!(*recursion, 0, "Re... | {
// Lock is managed by kernelspace. Call into the kernel
// to unblock waiting threads.
let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE);
assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex");
} | conditional_block |
mutex.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub unsafe fn uninitialized() -> ReentrantMutex {
mem::uninitialized()
}
pub unsafe fn init(&mut self) {
self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0));
self.recursion = UnsafeCell::new(0);
}
pub unsafe fn try_lock(&self) -> bool {
// Attempt to a... |
impl ReentrantMutex { | random_line_split |
mutex.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) {
self.0.write()
}
pub unsafe fn unlock(&self) {
self.0.write_unlock()
}
pub unsafe fn destroy(&self) {
self.0.destroy()
}
}
pub struct ReentrantMutex {
lock: UnsafeCell<AtomicU32>,
recursion: UnsafeCell<u32>,
}
impl ReentrantMutex {
pub unsafe fn unin... | lock | identifier_name |
mutex.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub unsafe fn init(&mut self) {
// This function should normally reinitialize the mutex after
// moving it to a different memory address. This implementation
// does not require adjustments after moving.
}
pub unsafe fn try_lock(&self) -> bool {
self.0.try_write()
}
... | {
Mutex(RWLock::new())
} | identifier_body |
stack.rs | //! Provides functionality to manage multiple stacks.
use arch::{self, Architecture};
use core::cmp::{max, min};
use core::fmt;
use core::mem::size_of;
use memory::address_space::{AddressSpace, Segment, SegmentType};
use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE};
// NOTE: For now only ... |
}
| {
let current_size = (self.top_address - self.bottom_address) as isize;
let difference = new_size as isize - current_size;
if difference > 0 {
self.grow(difference as usize, address_space);
} else {
self.shrink(-difference as usize, address_space);
}
... | identifier_body |
stack.rs | //! Provides functionality to manage multiple stacks.
use arch::{self, Architecture};
use core::cmp::{max, min};
use core::fmt;
use core::mem::size_of;
use memory::address_space::{AddressSpace, Segment, SegmentType};
use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE};
// NOTE: For now only ... |
let area = MemoryArea::new(start_address, max_size);
assert!(
address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)),
"Could not add stack segment."
);
}
stack.resize(initial_size, address_space);
sta... | {
flags |= USER_ACCESSIBLE;
} | conditional_block |
stack.rs | //! Provides functionality to manage multiple stacks.
use arch::{self, Architecture};
use core::cmp::{max, min};
use core::fmt;
use core::mem::size_of;
use memory::address_space::{AddressSpace, Segment, SegmentType};
use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE};
// NOTE: For now only ... | "Bottom: {:?}, Top: {:?}, Max size: {:x}",
self.bottom_address, self.top_address, self.max_size
)
}
}
impl Drop for Stack {
fn drop(&mut self) {
// NOTE: This assumes that the stack is dropped in its own address space.
self.resize(0, None);
}
}
impl Stack {
... | random_line_split | |
stack.rs | //! Provides functionality to manage multiple stacks.
use arch::{self, Architecture};
use core::cmp::{max, min};
use core::fmt;
use core::mem::size_of;
use memory::address_space::{AddressSpace, Segment, SegmentType};
use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE};
// NOTE: For now only ... | {
/// Represents the top address of the stack.
top_address: VirtualAddress,
/// Represents the bottom address of the stack.
bottom_address: VirtualAddress,
/// Represents the maximum stack size.
max_size: usize,
/// Represents the first address of the stack.
pub base_stack_pointer: Virt... | Stack | identifier_name |
animations.rs | //! Animation effects embedded in the game world.
use crate::{location::Location, world::World};
use calx::{ease, project, CellSpace, ProjectVec, Space};
use calx_ecs::Entity;
use euclid::{vec2, Vector2D, Vector3D};
use serde::{Deserialize, Serialize};
/// Location with a non-integer offset delta.
///
/// Use for twe... | (&self, e: Entity) -> Option<LerpLocation> {
if let Some(location) = self.location(e) {
Some(LerpLocation {
location,
offset: self.lerp_offset(e),
})
} else {
None
}
}
pub fn lerp_offset(&self, e: Entity) -> PhysicsVect... | lerp_location | identifier_name |
animations.rs | use euclid::{vec2, Vector2D, Vector3D};
use serde::{Deserialize, Serialize};
/// Location with a non-integer offset delta.
///
/// Use for tweened animations.
#[derive(Copy, Clone, PartialEq, Debug, Default)]
pub struct LerpLocation {
pub location: Location,
pub offset: PhysicsVector,
}
impl From<Location> fo... | //! Animation effects embedded in the game world.
use crate::{location::Location, world::World};
use calx::{ease, project, CellSpace, ProjectVec, Space};
use calx_ecs::Entity; | random_line_split | |
animations.rs | //! Animation effects embedded in the game world.
use crate::{location::Location, world::World};
use calx::{ease, project, CellSpace, ProjectVec, Space};
use calx_ecs::Entity;
use euclid::{vec2, Vector2D, Vector3D};
use serde::{Deserialize, Serialize};
/// Location with a non-integer offset delta.
///
/// Use for twe... |
}
pub fn lerp_offset(&self, e: Entity) -> PhysicsVector {
if let Some(location) = self.location(e) {
if let Some(anim) = self.anim(e) {
let frame = (self.get_anim_tick() - anim.tween_start) as u32;
if frame < anim.tween_duration {
if let ... | {
None
} | conditional_block |
errors.rs | use rstest::*;
#[fixture]
pub fn fixture() -> u32 { 42 }
#[fixture]
fn error_inner(fixture: u32) {
let a: u32 = "";
}
#[fixture]
fn error_cannot_resolve_fixture(no_fixture: u32) {
}
#[fixture]
fn error_fixture_wrong_type(fixture: String) {
}
#[fixture(not_a_fixture(24))]
fn error_inject_an_invalid_fixture(fixt... |
#[fixture]
#[once]
async fn error_async_once_fixture() {
}
#[fixture]
#[once]
fn error_generics_once_fixture<T: std::fmt::Debug>() -> T {
42
}
#[fixture]
#[once]
fn error_generics_once_fixture() -> impl Iterator<Item: u32> {
std::iter::once(42)
}
| {
} | identifier_body |
errors.rs | use rstest::*;
#[fixture]
pub fn fixture() -> u32 { 42 }
#[fixture]
fn error_inner(fixture: u32) {
let a: u32 = "";
}
#[fixture]
fn error_cannot_resolve_fixture(no_fixture: u32) {
}
#[fixture]
fn error_fixture_wrong_type(fixture: String) {
}
#[fixture(not_a_fixture(24))]
fn error_inject_an_invalid_fixture(fixt... | fn error_generics_once_fixture() -> impl Iterator<Item: u32> {
std::iter::once(42)
} | }
#[fixture]
#[once] | random_line_split |
errors.rs | use rstest::*;
#[fixture]
pub fn fixture() -> u32 { 42 }
#[fixture]
fn error_inner(fixture: u32) {
let a: u32 = "";
}
#[fixture]
fn error_cannot_resolve_fixture(no_fixture: u32) {
}
#[fixture]
fn error_fixture_wrong_type(fixture: String) {
}
#[fixture(not_a_fixture(24))]
fn error_inject_an_invalid_fixture(fixt... | (name: &str) -> String {
name.to_owned()
}
#[fixture(f("first"), f("second"))]
fn error_inject_a_fixture_more_than_once(f: String) {
}
#[fixture]
#[once]
async fn error_async_once_fixture() {
}
#[fixture]
#[once]
fn error_generics_once_fixture<T: std::fmt::Debug>() -> T {
42
}
#[fixture]
#[once]
fn error_ge... | f | identifier_name |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, M... | "{}\r\nContent-Disposition: form-data; name=\"{}\"",
boundary, field.name
)?;
if let Some(filename) = filename {
write!(buf, "; filename=\"{}\"", filename)?;
}
write!... | {
let mut boundary = format!("\r\n--{}", gen_boundary());
let mut buf: Vec<u8> = Vec::new();
for field in self.fields.drain(..) {
match field.data {
Data::Text(value) => {
write!(
buf,
"{}\r\nConten... | identifier_body |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, M... | <'a> {
Text(String),
File(PathBuf),
Stream(Stream<'a>),
}
impl<'a> fmt::Debug for Data<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Data::Text(ref value) => write!(f, "Data::Text({:?})", value),
Data::File(ref path) => write!(f, "Data::File(... | Data | identifier_name |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, M... | V: Into<String>,
{
let filed = Field {
name: name.into(),
data: Data::Text(value.into()),
};
self.fields.push(filed);
self
}
/// Add file into `Multipart`.
///
/// # Examples
///
/// ```no_test
/// use sincere::http::plus... | where | random_line_split |
multipart.rs | use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::PathBuf;
use mime_guess;
use crate::error::Result;
use crate::http::plus::random_alphanumeric;
const BOUNDARY_LEN: usize = 32;
fn gen_boundary() -> String {
random_alphanumeric(BOUNDARY_LEN)
}
use crate::http::mime::{self, M... |
Data::File(path) => {
let (content_type, filename) = mime_filename(&path);
let mut file = File::open(&path)?;
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"",
... | {
write!(
buf,
"{}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{}",
boundary, field.name, value
)?;
} | conditional_block |
default.rs | // Copyright 2012-2013 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... | }
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.... | {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: Lifetim... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.