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 |
|---|---|---|---|---|
time.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | use super::NSEC_PER_SEC;
pub struct SteadyTime {
t: libc::timespec,
}
// Apparently android provides this in some other library?
// Bitrig's RT extensions are in the C library, not a separate librt
// OpenBSD provide it via libc
#[cfg(not(any(target_os = "android",
... | #[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod inner {
use libc;
use time::Duration;
use ops::Sub; | random_line_split |
time.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> SteadyTime {
SteadyTime {
t: unsafe { mach_absolute_time() },
}
}
}
fn info() -> &'static libc::mach_timebase_info {
static mut INFO: libc::mach_timebase_info = libc::mach_timebase_info {
numer: 0,
denom: 0,
};
... | now | identifier_name |
time.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod inner {
use libc;
use time::Duration;
use ops::Sub;
use super::NSEC_PER_SEC;
pub struct SteadyTime {
t: libc::timespec,
}
// Apparently android provides this in some other library?
// Bitrig's RT extensions ... | {
let info = info();
let diff = self.t as u64 - other.t as u64;
let nanos = diff * info.numer as u64 / info.denom as u64;
Duration::new(nanos / NSEC_PER_SEC, (nanos % NSEC_PER_SEC) as u32)
} | identifier_body |
time.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
Duration::new(self.t.tv_sec as u64 - 1 - other.t.tv_sec as u64,
self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) -
other.t.tv_nsec as u32)
}
}
}
}
| {
Duration::new(self.t.tv_sec as u64 - other.t.tv_sec as u64,
self.t.tv_nsec as u32 - other.t.tv_nsec as u32)
} | conditional_block |
test_register_deregister.rs | use mio::*;
use mio::net::*;
use mio::net::tcp::*;
use super::localhost;
use std::time::Duration;
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
type TestEventLoop = EventLoop<usize, ()>;
struct TestHandler {
server: TcpAcceptor,
client: TcpSocket,
state: usize,
}
impl TestHandler {
... | (&mut self, event_loop: &mut TestEventLoop, token: Token, _: ReadHint) {
match token {
SERVER => {
let sock = self.server.accept().unwrap().unwrap();
sock.write(&mut buf::SliceBuf::wrap("foobar".as_bytes())).unwrap();
}
CLIENT => {
... | readable | identifier_name |
test_register_deregister.rs | use mio::*;
use mio::net::*;
use mio::net::tcp::*;
use super::localhost;
use std::time::Duration;
const SERVER: Token = Token(0);
const CLIENT: Token = Token(1);
type TestEventLoop = EventLoop<usize, ()>;
struct TestHandler {
server: TcpAcceptor,
client: TcpSocket,
state: usize,
}
impl TestHandler {
... | event_loop.register_opt(&client, CLIENT, Interest::readable(), PollOpt::level()).unwrap();
let server = server.bind(&addr).unwrap().listen(256).unwrap();
info!("register server socket");
event_loop.register_opt(&server, SERVER, Interest::readable(), PollOpt::edge()).unwrap();
// Connect to the se... | let client = TcpSocket::v4().unwrap();
// Register client socket only as writable | random_line_split |
password.rs | // Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
//! Password verification.
/// The scrypt password hashing function.
///
/// scrypt was originally proposed in [Stronger Key Derivation ... |
boringssl::crypto_memcmp(&out_hash, &hash.hash)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_scrypt() {
for _ in 0..16 {
let mut pass = [0; 128];
boringssl::rand_bytes(&mut pass);
// target 1 second of... | {
return false;
} | conditional_block |
password.rs | // Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
//! Password verification.
/// The scrypt password hashing function.
///
/// scrypt was originally proposed in [Stronger Key Derivation ... | (&self) -> u64 {
self.p
}
}
// Don't put a limit on the memory used by scrypt; it's too prone to
// failure. Instead, rely on choosing sane defaults for N, r, and p to
// ensure that we don't use too much memory.
const SCRYPT_MAX_MEM: usize = usize::max_value();
// TODO(jos... | p | identifier_name |
password.rs | // Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
//! Password verification.
/// The scrypt password hashing function.
///
/// scrypt was originally proposed in [Stronger Key Derivation ... | r: u64,
p: u64,
}
impl ScryptParams {
/// Gets the parameter N.
#[allow(non_snake_case)]
#[must_use]
pub fn N(&self) -> u64 {
self.N
}
/// Gets the parameter r.
#[must_use]
pub fn r(&self) -> u64 {
self.r
... | // NOTE(joshlf): These are private so that the user is forced to use one
// of our presets. If this turns out to be too brittle, it might be
// worth considering making these public, and simply discouraging
// (perhaps via a deprecation attribute) setting them directly.
N: u64, | random_line_split |
password.rs | // Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
//! Password verification.
/// The scrypt password hashing function.
///
/// scrypt was originally proposed in [Stronger Key Derivation ... |
}
// Don't put a limit on the memory used by scrypt; it's too prone to
// failure. Instead, rely on choosing sane defaults for N, r, and p to
// ensure that we don't use too much memory.
const SCRYPT_MAX_MEM: usize = usize::max_value();
// TODO(joshlf): Provide a custom Debug impl for ScryptH... | {
self.p
} | identifier_body |
mod.rs | tainted_region));
} else {
debug!("Overly polymorphic!");
return Err(ty::terr_regions_overly_polymorphic(skol_br,
... | (infcx: &InferCtxt,
span: Span,
snapshot: &CombinedSnapshot,
debruijn: ty::DebruijnIndex,
new_vars: &[ty::RegionVid],
a_map: &FnvHashMap<ty::BoundRegion, ty::Region>,
... | generalize_region | identifier_name |
mod.rs | tainted_region));
} else {
debug!("Overly polymorphic!");
return Err(ty::terr_regions_overly_polymorphic(skol_br,
... | let result1 =
fold_regions_in(
self.tcx(),
&result0,
|r, debruijn| generalize_region(self.infcx, span, snapshot, debruijn,
&new_vars,
... | random_line_split | |
mod.rs | tainted_region));
} else {
debug!("Overly polymorphic!");
return Err(ty::terr_regions_overly_polymorphic(skol_br,
... |
// Otherwise, the variable must be associated with at
// least one of the variables representing bound regions
// in both A and B. Replace the variable with the "first"
// bound region from A that we find it to be associated
// with.
for (a_br, a... | {
// Regions that pre-dated the LUB computation stay as they are.
if !is_var_in_set(new_vars, r0) {
assert!(!r0.is_bound());
debug!("generalize_region(r0={:?}): not new variable", r0);
return r0;
}
let tainted = infcx.taint... | identifier_body |
mod.rs | tainted_region));
} else {
debug!("Overly polymorphic!");
return Err(ty::terr_regions_overly_polymorphic(skol_br,
... | else {
a_r = Some(*r);
}
} else if is_var_in_set(b_vars, *r) {
if b_r.is_some() {
return fresh_bound_variable(infcx, debruijn);
} else {
b_r = Some(*r);
... | {
return fresh_bound_variable(infcx, debruijn);
} | conditional_block |
test_mount.rs | // Impelmentation note: to allow unprivileged users to run it, this test makes
// use of user and mount namespaces. On systems that allow unprivileged user
// namespaces (Linux >= 3.8 compiled with CONFIG_USER_NS), the test should run
// without root.
extern crate libc;
extern crate nix;
extern crate tempdir;
#[cfg(t... | () {
// Hold on to the uid in the parent namespace.
let uid = getuid();
unshare(CLONE_NEWNS | CLONE_NEWUSER).unwrap_or_else(|e| {
let stderr = io::stderr();
let mut handle = stderr.lock();
writeln!(handle,
"unshare failed: {}. Are unprivi... | setup_namespaces | identifier_name |
test_mount.rs | // Impelmentation note: to allow unprivileged users to run it, this test makes
// use of user and mount namespaces. On systems that allow unprivileged user
// namespaces (Linux >= 3.8 compiled with CONFIG_USER_NS), the test should run
// without root.
extern crate libc;
extern crate nix;
extern crate tempdir;
#[cfg(t... | Command::new(&test_path).status().unwrap_err().raw_os_error().unwrap());
umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e));
}
pub fn test_mount_bind() {
use std::env;
if env::var("CI").is_ok() && env::var("TRAVIS").is_ok() {
print!... | random_line_split | |
test_mount.rs | // Impelmentation note: to allow unprivileged users to run it, this test makes
// use of user and mount namespaces. On systems that allow unprivileged user
// namespaces (Linux >= 3.8 compiled with CONFIG_USER_NS), the test should run
// without root.
extern crate libc;
extern crate nix;
extern crate tempdir;
#[cfg(t... |
let tempdir = TempDir::new("nix-test_mount")
.unwrap_or_else(|e| panic!("tempdir failed: {}", e));
let file_name = "test";
{
let mount_point = TempDir::new("nix-test_mount")
.unwrap_or_else(|e| panic!("tempdir failed: {}", ... | {
print!("Travis does not allow bind mounts, skipping.");
return;
} | conditional_block |
test_mount.rs | // Impelmentation note: to allow unprivileged users to run it, this test makes
// use of user and mount namespaces. On systems that allow unprivileged user
// namespaces (Linux >= 3.8 compiled with CONFIG_USER_NS), the test should run
// without root.
extern crate libc;
extern crate nix;
extern crate tempdir;
#[cfg(t... |
pub fn test_mount_noexec_disallows_exec() {
let tempdir = TempDir::new("nix-test_mount")
.unwrap_or_else(|e| panic!("tempdir failed: {}", e));
mount(NONE,
tempdir.path(),
Some(b"tmpfs".as_ref()),
MS_NOEXEC,
NONE)
... | {
let tempdir = TempDir::new("nix-test_mount")
.unwrap_or_else(|e| panic!("tempdir failed: {}", e));
mount(NONE,
tempdir.path(),
Some(b"tmpfs".as_ref()),
MS_RDONLY,
NONE)
.unwrap_or_else(|e| panic!("mount fail... | identifier_body |
handler.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... | () {
// given
let path1 = "/";
let path2= "/test.css";
let path3 = "/app/myfile.txt";
let path4 = "/app/myfile.txt?query=123";
let page_handler = PageHandler {
app: test::TestWebapp,
prefix: None,
path: EndpointPath {
app_id: "app".to_owned(),
app_params: vec![],
host: "".to_owned(),
port: 8080... | should_extract_path_with_appid | identifier_name |
handler.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... | f.bytes_written(bytes);
Next::write()
},
Err(e) => match e.kind() {
::std::io::ErrorKind::WouldBlock => Next::write(),
_ => Next::end(),
},
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
pub struct TestWebAppFile;
impl DappFile for TestWebAppFile {
fn content_type(&self) -... | ServedFile::File(ref f) if f.is_drained() => Next::end(),
ServedFile::File(ref mut f) => match encoder.write(f.next_chunk()) {
Ok(bytes) => { | random_line_split |
handler.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... |
}
/// A generic type for `PageHandler` allowing to set the URL.
/// Used by dapps fetching to set the URL after the content was downloaded.
pub trait PageHandlerWaiting: server::Handler<HttpStream> + Send {
fn set_uri(&mut self, uri: &RequestUri);
}
/// A handler for a single webapp.
/// Resolves correct paths and ... | {
PageCache::Disabled
} | identifier_body |
token.rs | use std::fmt;
/// Represents the type of a token
#[derive(Debug, Clone, PartialEq)]
pub enum TokenType {
Block(Vec<Token>),
IntLiteral,
FloatLiteral,
Keyword,
Symbol,
Operator,
Identifier,
Whitespace,
StringLiteral,
CharLiteral,
BooleanLiteral,
LiteralStringLiteral,
... |
}
impl Token {
pub fn new(token_type: TokenType, position: TokenPosition, content: String) -> Token {
Token {
token_type: token_type,
position: position,
content: content,
}
}
// Immutable access
pub fn token_type(&self) -> &TokenType {
&sel... | {
write!(f,
"Token({}, {:?} '{}')",
self.position,
self.token_type,
self.content)
} | identifier_body |
token.rs | use std::fmt;
/// Represents the type of a token
#[derive(Debug, Clone, PartialEq)]
pub enum TokenType {
Block(Vec<Token>),
IntLiteral,
FloatLiteral,
Keyword,
Symbol,
Operator,
Identifier,
Whitespace,
StringLiteral,
CharLiteral,
BooleanLiteral,
LiteralStringLiteral,
... | (&mut self) -> &mut TokenPosition {
&mut self.position
}
}
impl<'a> PartialEq for Token {
fn eq(&self, other: &Token) -> bool {
&self.token_type == other.token_type()
}
fn ne(&self, other: &Token) -> bool {
&self.token_type!= other.token_type()
}
} | position_mut | identifier_name |
token.rs | use std::fmt;
/// Represents the type of a token
#[derive(Debug, Clone, PartialEq)]
pub enum TokenType {
Block(Vec<Token>),
IntLiteral,
FloatLiteral,
Keyword,
Symbol,
Operator,
Identifier,
Whitespace,
StringLiteral,
CharLiteral,
BooleanLiteral,
LiteralStringLiteral,
... | &mut self.token_type
}
pub fn position_mut(&mut self) -> &mut TokenPosition {
&mut self.position
}
}
impl<'a> PartialEq for Token {
fn eq(&self, other: &Token) -> bool {
&self.token_type == other.token_type()
}
fn ne(&self, other: &Token) -> bool {
&self.token_... | }
// Mutable access
pub fn token_type_mut(&mut self) -> &mut TokenType { | random_line_split |
resource_thread.rs | ProgressSender::Channel(ref c) => c.send(msg).map_err(|_| ()),
}
}
}
pub fn send_error(url: ServoUrl, err: NetworkError, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
if let Ok(p) = start_sending_opt(start_chan, metadata) {
p.... | where T: Decodable
{
let path = config_dir.join(filename);
let display = path.display();
let mut file = match File::open(&path) {
Err(why) => {
warn!("couldn't open {}: {}", display, Error::description(&why));
return;
},
Ok(file) => file,
};
let ... | true
}
}
pub fn read_json_from_file<T>(data: &mut T, config_dir: &Path, filename: &str) | random_line_split |
resource_thread.rs | Sender::Channel(ref c) => c.send(msg).map_err(|_| ()),
}
}
}
pub fn send_error(url: ServoUrl, err: NetworkError, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
if let Ok(p) = start_sending_opt(start_chan, metadata) {
p.send(Done... |
let _ = sender.send(());
return false;
}
}
true
}
}
pub fn read_json_from_file<T>(data: &mut T, config_dir: &Path, filename: &str)
where T: Decodable
{
let path = config_dir.join(filename);
let display = path.display();
let mut file = ma... | {
match group.auth_cache.read() {
Ok(auth_cache) => write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"),
Err(_) => warn!("Error writing auth cache to disk"),
}
match group.cookie_jar.read() {
... | conditional_block |
resource_thread.rs | config_dir: Option<PathBuf>)
-> (ResourceThreads, ResourceThreads) {
let (public_core, private_core) = new_core_resource_thread(
user_agent,
devtools_chan,
profiler_chan,
config_dir.clone());
let storage: IpcSender<StorageThreadMsg> = Stora... | {
let http_state = HttpState {
hsts_list: group.hsts_list.clone(),
cookie_jar: group.cookie_jar.clone(),
auth_cache: group.auth_cache.clone(),
blocked_content: BLOCKED_CONTENT_RULES.clone(),
};
let ua = self.user_agent.clone();
let dc = sel... | identifier_body | |
resource_thread.rs | Sender::Channel(ref c) => c.send(msg).map_err(|_| ()),
}
}
}
pub fn send_error(url: ServoUrl, err: NetworkError, start_chan: LoadConsumer) {
let mut metadata: Metadata = Metadata::default(url);
metadata.status = None;
if let Ok(p) = start_sending_opt(start_chan, metadata) {
p.send(Done... | (config_dir: Option<&Path>)
-> (ResourceGroup, ResourceGroup) {
let mut hsts_list = HstsList::from_servo_preload();
let mut auth_cache = AuthCache::new();
let mut cookie_jar = CookieStorage::new();
if let Some(config_dir) = config_dir {
read_json_from_file(&mut auth_cac... | create_resource_groups | identifier_name |
delete_pushrule.rs | //! [DELETE /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}](https://matrix.org/docs/spec/client_server/r0.6.0#delete-matrix-client-r0-pushrules-scope-kind-ruleid)
use ruma_api::ruma_api;
use super::RuleKind;
ruma_api! {
metadata {
description: "This endpoint removes the push rule defined in the pat... |
/// The kind of rule
#[ruma_api(path)]
pub kind: RuleKind,
/// The identifier for the rule.
#[ruma_api(path)]
pub rule_id: String,
}
response {}
error: crate::Error
} | random_line_split | |
lib.rs | //! Utility macro for creating convenient fixed-size `u8` arrays.
//!
//! # Example
//! ```
//! #[macro_use]
//! extern crate byte_array;
//!
//! byte_array!(MyArray[1024] with u16 indexing please);
//! byte_array!(AnotherArray[100]);
//!
//! fn main() {
//! let mut array = MyArray::default();
//! array[0u16] =... | ( $name:ident | with $($rest:tt)+ ) => { impl_byte_array_extra!( $name | $($rest)* ); };
( $name:ident |, $($rest:tt)+ ) => { impl_byte_array_extra!( $name | $($rest)* ); };
( $name:ident | please ) => {};
( $name:ident | ) => {};
}
#[macro_export]
#[doc = "hidden"]
macro_rules! impl_byte_array {
(... | }
}
impl_byte_array_extra!( $name | $($rest)* );
};
| random_line_split |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The implementation of the DOM.
//!
//! The DOM is comprised of interfaces (defined by specifications using
//!... | //! instance of the superclass in the first field of its subclasses. (Note that
//! it is stored by value, rather than in a smart pointer such as `JS<T>`.)
//!
//! This implies that a pointer to an object can safely be cast to a pointer
//! to all its classes.
//!
//! This invariant is enforced by the lint in
//! `plug... | //! object-oriented DOM APIs. To work around this issue, Servo stores an | random_line_split |
image.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/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-value... |
/// <https://drafts.csswg.org/css-images/#typedef-extent-keyword>
#[allow(missing_docs)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq)]
#[derive(ToComputedValue, ToCss)]
pub enum ShapeExtent {
ClosestSide,
FarthestSide,
Close... | Radii(LengthOrPercentage, LengthOrPercentage),
/// An ellipse extent.
Extent(ShapeExtent),
} | random_line_split |
image.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/. */
//! Generic types for the handling of [images].
//!
//! [images]: https://drafts.csswg.org/css-images/#image-value... | <LineDirection, Length, LengthOrPercentage, Position, Angle> {
/// A linear gradient.
Linear(LineDirection),
/// A radial gradient.
Radial(EndingShape<Length, LengthOrPercentage>, Position, Option<Angle>),
}
/// A radial gradient's ending shape.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToC... | GradientKind | identifier_name |
day04.rs | extern crate regex;
use std::char;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::io::{BufReader, BufRead};
use std::fs::File;
use regex::Regex;
struct Room {
name: String,
sector_id: u32,
checksum: String,
}
impl Room {
fn new(room: &str) -> Self {
let re = Regex::new(r"([a-... | (&self) -> bool {
let mut counts = HashMap::new();
for c in self.name.chars() {
if c!= '-' {
*counts.entry(c).or_insert(0) += 1;
}
}
let mut freqs: Vec<_> = counts.into_iter().collect();
freqs.sort_by(|a, b| {
match a.1.cmp(&b... | is_valid | identifier_name |
day04.rs | extern crate regex;
use std::char;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::io::{BufReader, BufRead};
use std::fs::File;
use regex::Regex;
struct Room {
name: String,
sector_id: u32,
checksum: String,
}
impl Room {
fn new(room: &str) -> Self {
let re = Regex::new(r"([a-... | else {
(((ch as u8) - b'a' + shift) % 26 + b'a') as char
}
).collect()
}
}
fn main() {
let file = File::open("input/day04.in").expect("Failed to open input");
let reader = BufReader::new(&file);
let mut sum_sector_ids = 0;
let mut part2_ans = 0;
for line i... | {
' '
} | conditional_block |
day04.rs | extern crate regex;
use std::char;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::io::{BufReader, BufRead};
use std::fs::File;
use regex::Regex;
struct Room {
name: String,
sector_id: u32,
checksum: String,
}
impl Room {
fn new(room: &str) -> Self {
let re = Regex::new(r"([a-... |
}
fn main() {
let file = File::open("input/day04.in").expect("Failed to open input");
let reader = BufReader::new(&file);
let mut sum_sector_ids = 0;
let mut part2_ans = 0;
for line in reader.lines() {
let line = line.unwrap();
let room = Room::new(&line);
if room.is_val... | {
let shift = (self.sector_id % 26) as u8;
self.name.chars().map(|ch|
if ch == '-' {
' '
} else {
(((ch as u8) - b'a' + shift) % 26 + b'a') as char
}
).collect()
} | identifier_body |
day04.rs | extern crate regex;
use std::char;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::io::{BufReader, BufRead};
use std::fs::File;
use regex::Regex;
struct Room {
name: String,
sector_id: u32,
checksum: String,
} | let re = Regex::new(r"([a-z-]+)-(\d+)\[([a-z]+)]").unwrap();
let cap = re.captures(room).unwrap();
Room{
name: cap.at(1).unwrap().to_owned(),
sector_id: cap.at(2).unwrap().parse().unwrap(),
checksum: cap.at(3).unwrap().to_owned(),
}
}
fn is_v... |
impl Room {
fn new(room: &str) -> Self { | random_line_split |
resolve.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.resolve_type(t)
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
self.resolve_region(r)
}
}
impl<'a> ResolveState<'a> {
pub fn should(&mut self, mode: uint) -> bool {
(self.modes & mode) == mode
}
pub fn resolve_type_chk(&mut self, typ: ty::t) -> fres<ty... | fn tcx<'a>(&'a self) -> &'a ty::ctxt {
self.infcx.tcx
}
fn fold_ty(&mut self, t: ty::t) -> ty::t { | random_line_split |
resolve.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 ... |
}
| {
if !self.should(resolve_fvar) {
return ty::mk_float_var(self.infcx.tcx, vid);
}
let node = self.infcx.get(vid);
match node.possible_types {
Some(t) => ty::mk_mach_float(t),
None => {
if self.should(force_fvar) {
// As a last ... | identifier_body |
resolve.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 ... | else {
self.v_seen.push(vid);
let tcx = self.infcx.tcx;
// Nonobvious: prefer the most specific type
// (i.e., the lower bound) to the more general
// one. More general types in Rust (e.g., fn())
// tend to carry more restrictions or higher
... | {
self.err = Some(cyclic_ty(vid));
return ty::mk_var(self.infcx.tcx, vid);
} | conditional_block |
resolve.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 ... | (&mut self, rid: RegionVid) -> ty::Region {
if!self.should(resolve_rvar) {
return ty::ReInfer(ty::ReVar(rid));
}
self.infcx.region_vars.resolve_var(rid)
}
pub fn resolve_ty_var(&mut self, vid: TyVid) -> ty::t {
if self.v_seen.contains(&vid) {
self.err = S... | resolve_region_var | identifier_name |
error.rs | use std::io::IoError;
use std::error::{Error, FromError};
/// Possible parser errors
#[derive(Show, PartialEq)]
pub enum ParserErrorKind {
/// Parser met EOF before parsing a proper datum
UnexpectedEOF,
/// Unexpected token: the first string describes expected token, and the second describes
/// actual... |
}
/// Possible compiler errors
#[derive(Show, PartialEq, Copy)]
pub enum CompileErrorKind {
/// The syntax is not implemented yet
NotImplemented,
/// Trying to evaluate `()`
NullEval,
/// Trying to evaluate non-proper list, such as `(a b c. d)`
DottedEval,
/// Expression body is non-proper... | {
ParserError {
line: 0,
column: 0,
kind: ParserErrorKind::UnderlyingError(err)
}
} | identifier_body |
error.rs | use std::io::IoError;
use std::error::{Error, FromError};
/// Possible parser errors
#[derive(Show, PartialEq)]
pub enum | {
/// Parser met EOF before parsing a proper datum
UnexpectedEOF,
/// Unexpected token: the first string describes expected token, and the second describes
/// actual token
UnexpectedToken(String, String),
/// Lexer met character not allowed in source code
InvalidCharacter(char),
/// Pa... | ParserErrorKind | identifier_name |
error.rs | use std::io::IoError;
use std::error::{Error, FromError};
/// Possible parser errors
#[derive(Show, PartialEq)]
pub enum ParserErrorKind {
/// Parser met EOF before parsing a proper datum
UnexpectedEOF,
/// Unexpected token: the first string describes expected token, and the second describes
/// actual... | }
fn detail(&self) -> Option<String> {
None
}
fn cause(&self) -> Option<&Error> {
match self.kind {
ParserErrorKind::UnderlyingError(ref e) => Some(e as &Error),
_ => None
}
}
}
impl FromError<IoError> for ParserError {
fn from_error(err: IoErro... | random_line_split | |
lexical-scope-in-unique-closure.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 sentinel() {()}
| {()} | identifier_body |
lexical-scope-in-unique-closure.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... | () {()}
| sentinel | identifier_name |
lexical-scope-in-unique-closure.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. | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:p... | //
// 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 | random_line_split |
vpcmpistrm.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vpcmpistrm_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRM, operand1: Some(Direct(XMM7)), operand2: Some(D... | {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRM, operand1: Some(Direct(XMM3)), operand2: Some(IndirectScaledIndexedDisplaced(RBX, RDX, Two, 85643390, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(13)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None,... | identifier_body | |
vpcmpistrm.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vpcmpistrm_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRM, operand1: Some(Direct(XMM7)), operand2: Some(D... | fn vpcmpistrm_3() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRM, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(14)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 98, 196, 14], OperandS... | }
| random_line_split |
vpcmpistrm.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vpcmpistrm_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRM, operand1: Some(Direct(XMM7)), operand2: Some(D... | () {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRM, operand1: Some(Direct(XMM5)), operand2: Some(IndirectDisplaced(EBX, 1248272946, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(115)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None ... | vpcmpistrm_2 | identifier_name |
file_loader.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 resource_task::{Done, LoaderTask, Payload};
use core::io::{ReaderUtil, file_reader};
use core::task;
static READ_SIZE: uint = 1024;
pub fn factory() -> LoaderTask {
let f: LoaderTask = |url, progress_chan| {
assert!("file" == url.scheme);
do ta... | random_line_split | |
file_loader.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 resource_task::{Done, LoaderTask, Payload};
use core::io::{ReaderUtil, file_reader};
use core::task;
static ... |
};
f
}
| {
let f: LoaderTask = |url, progress_chan| {
assert!("file" == url.scheme);
do task::spawn {
// FIXME: Resolve bug prevents us from moving the path out of the URL.
match file_reader(&Path(url.path)) {
Ok(reader) => {
while !reader.eof() {
let data = reader.read_bytes(READ_SIZE);
progress... | identifier_body |
file_loader.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 resource_task::{Done, LoaderTask, Payload};
use core::io::{ReaderUtil, file_reader};
use core::task;
static ... | () -> LoaderTask {
let f: LoaderTask = |url, progress_chan| {
assert!("file" == url.scheme);
do task::spawn {
// FIXME: Resolve bug prevents us from moving the path out of the URL.
match file_reader(&Path(url.path)) {
Ok(reader) => {
while!reader.eof() {
let data = reader.read_bytes(READ_SIZE)... | factory | identifier_name |
mod.rs | use chrono::{offset::Utc, DateTime}; | pub mod post;
use crate::{
base_actor::BaseActor,
base_post::direct_post::DirectPost,
file::image::Image,
generate_urls::GenerateUrls,
schema::base_posts,
sql_types::{Mime, PostVisibility},
};
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "base_posts"]
pub struct BasePost {
i... | use diesel::{self, pg::PgConnection};
use uuid::Uuid;
pub mod direct_post; | random_line_split |
mod.rs | use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use uuid::Uuid;
pub mod direct_post;
pub mod post;
use crate::{
base_actor::BaseActor,
base_post::direct_post::DirectPost,
file::image::Image,
generate_urls::GenerateUrls,
schema::base_posts,
sql_types::{Mime, PostVisib... | (
&self,
actor: &BaseActor,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
match self.visibility {
PostVisibility::Public => Ok(true),
PostVisibility::FollowersOnly => actor.is_following_id(self.posted_by, conn),
PostVisibility::Li... | is_visible_by | identifier_name |
mod.rs | use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use uuid::Uuid;
pub mod direct_post;
pub mod post;
use crate::{
base_actor::BaseActor,
base_post::direct_post::DirectPost,
file::image::Image,
generate_urls::GenerateUrls,
schema::base_posts,
sql_types::{Mime, PostVisib... |
}
#[cfg(test)]
mod tests {
use crate::test_helper::*;
#[test]
fn create_base_post() {
with_connection(|conn| {
with_base_actor(conn, |posted_by| {
with_base_post(conn, &posted_by, |_| Ok(()))
})
})
}
}
| {
NewBasePost {
name,
media_type,
posted_by: posted_by.id(),
icon: icon.map(|i| i.id()),
visibility,
local_uuid: None,
activitypub_id,
}
} | identifier_body |
piston.rs | // # Graphics dependencies
// conrod = "0.54.0"
// piston = "0.33.0"
// piston_window = "0.61.0"
// piston2d-graphics = "0.21.1"
// pistoncore-glutin_window = "0.39.0"
// piston2d-opengl_graphics = "0.46.0"
extern crate conrod;
extern crate piston_window;
extern crate piston;
extern crate graphics;
exter... | // clear([1.0; 4], graphics);
// rectangle([1.0, 0.0, 0.0, 1.0], // red
// [0.0, 0.0, 100.0, 100.0],
// context.transform,
// graphics);
// });
// }
// }
//====================================================... | // .exit_on_esc(true).build().unwrap();
// while let Some(event) = window.next() {
// window.draw_2d(&event, |context, graphics| {
| random_line_split |
piston.rs | // # Graphics dependencies
// conrod = "0.54.0"
// piston = "0.33.0"
// piston_window = "0.61.0"
// piston2d-graphics = "0.21.1"
// pistoncore-glutin_window = "0.39.0"
// piston2d-opengl_graphics = "0.46.0"
extern crate conrod;
extern crate piston_window;
extern crate piston;
extern crate graphics;
exter... | let mut events = Events::new(EventSettings::new());
while let Some(e) = events.next(&mut window) {
if let Some(r) = e.render_args() {
app.render(&r);
}
if let Some(u) = e.update_args() {
app.update(&u);
}
}
}
//=============================================================================... | {
// Choose appropriate GL version
let opengl = OpenGL::V3_2;
// Create an Glutin window.
let mut window: Window = WindowSettings::new(
"spinning-square",
[200,200]
)
.opengl(opengl)
.exit_on_esc(true)
.build()
.unwrap();
// Create a new game and run it.
let mut app = App {
gl: GlGrap... | identifier_body |
piston.rs | // # Graphics dependencies
// conrod = "0.54.0"
// piston = "0.33.0"
// piston_window = "0.61.0"
// piston2d-graphics = "0.21.1"
// pistoncore-glutin_window = "0.39.0"
// piston2d-opengl_graphics = "0.46.0"
extern crate conrod;
extern crate piston_window;
extern crate piston;
extern crate graphics;
exter... |
}
}
//=====================================================================================
| {
app.update(&u);
} | conditional_block |
piston.rs | // # Graphics dependencies
// conrod = "0.54.0"
// piston = "0.33.0"
// piston_window = "0.61.0"
// piston2d-graphics = "0.21.1"
// pistoncore-glutin_window = "0.39.0"
// piston2d-opengl_graphics = "0.46.0"
extern crate conrod;
extern crate piston_window;
extern crate piston;
extern crate graphics;
exter... | (&mut self, args: &RenderArgs) {
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
let square = rectangle::square(0.0, 0.0, (args.width/4) as f64);
let rotation = self.rotation;
let (x,y) = ((args.width / 2) as f64,
(args.height / 2) as f64);
self.g... | render | identifier_name |
revocation_id_type.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").
//
// By ... |
/// Signs the data with the SecretKey of the AnMaid and recturns the Signed Data
pub fn sign(&self, data : &[u8]) -> Vec<u8> {
return ::sodiumoxide::crypto::sign::sign(&data, &self.secret_key)
}
}
#[cfg(test)]
mod test {
extern crate rand;
use super::RevocationIdType;
use self::rand:... | {
&self.public_key
} | identifier_body |
revocation_id_type.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").
//
// By ... | () {
let first_obj = RevocationIdType::generate_random();
let second_obj = RevocationIdType::generate_random();
let cloned_obj = second_obj.clone();
assert!(first_obj!= second_obj);
assert!(second_obj == cloned_obj);
}
#[test]
fn generation() {
let maid1 = R... | equality_assertion_an_maid | identifier_name |
revocation_id_type.rs | // Copyright 2015 MaidSafe.net limited. | // licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root director... | //
// 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 | random_line_split |
unwind-lambda.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 cheese = ~"roquefort";
let carrots = @~"crunchy";
let result: &'static fn(@~str, &fn(~str)) = (|tasties, macerate| {
macerate((*tasties).clone());
});
result(carrots, |food| {
let mush = food + cheese;
let cheese = cheese.clone();
let f: &fn() = || {
... | identifier_body | |
unwind-lambda.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 cheese = cheese.clone();
let f: &fn() = || {
let _chew = mush + cheese;
fail!("so yummy")
};
f();
});
} | let mush = food + cheese; | random_line_split |
unwind-lambda.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 cheese = ~"roquefort";
let carrots = @~"crunchy";
let result: &'static fn(@~str, &fn(~str)) = (|tasties, macerate| {
macerate((*tasties).clone());
});
result(carrots, |food| {
let mush = food + cheese;
let cheese = cheese.clone();
let f: &fn() = || {
... | main | identifier_name |
if_unmodified_since.rs | use header::HttpDate;
header! {
/// `If-Unmodified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4)
///
/// The `If-Unmodified-Since` header field makes the request method
/// conditional on the selected representation's last modification date
/// being ea... | ///
/// # Example
/// ```
/// use hyper::header::{Headers, IfUnmodifiedSince};
/// use std::time::{SystemTime, Duration};
///
/// let mut headers = Headers::new();
/// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// headers.set(IfUnmodifiedSince(modified.int... | /// * `Sat, 29 Oct 1994 19:43:31 GMT` | random_line_split |
main.rs | #[macro_use]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate handlebars;
mod controller;
mod data_type;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::prelude::*;
use handlebars::Handlebars;
use data_type::{TemplateContext, DayTemplate,... | (GET)(/peru) => {
controller::serve_index(&req)
},
_ => rouille::Response::empty_404()
)
},
);
}
// router.get("/blog", index_handler, "index_handler");
// router.get("/images/:imageId", handler, "handler");
//
// mount.mount("/im... | }, | random_line_split |
main.rs | #[macro_use]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate handlebars;
mod controller;
mod data_type;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::prelude::*;
use handlebars::Handlebars;
use data_type::{TemplateContext, DayTemplate,... |
}
router!(req,
(GET)(/peru/{id : i32}) => {
controller::serve_article(&req, &id)
},
(GET)(/peru) => {
controller::serve_index(&req)
},
_ => rouille::Response::empty_404()
)
},
);
... | {
return response;
} | conditional_block |
main.rs | #[macro_use]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate handlebars;
mod controller;
mod data_type;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::prelude::*;
use handlebars::Handlebars;
use data_type::{TemplateContext, DayTemplate,... | );
}
// router.get("/blog", index_handler, "index_handler");
// router.get("/images/:imageId", handler, "handler");
//
// mount.mount("/images/", Static::new(Path::new("content/images")));
// mount.mount("/images/min", Static::new(Path::new("content/images/min")));
// mount.mount("/style/", Static:... | {
println!("Server is running on {}", HOST);
rouille::start_server(HOST, move |req| {
//Serve static file
{
let response = rouille::match_assets(req, ".");
if response.is_success() {
return response;
}
}
router!(req,
... | identifier_body |
main.rs | #[macro_use]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate handlebars;
mod controller;
mod data_type;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::prelude::*;
use handlebars::Handlebars;
use data_type::{TemplateContext, DayTemplate,... | () {
println!("Server is running on {}", HOST);
rouille::start_server(HOST, move |req| {
//Serve static file
{
let response = rouille::match_assets(req, ".");
if response.is_success() {
return response;
}
}
router!(req,
... | main | identifier_name |
borrowck-mut-vec-as-imm-slice.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 ... |
pub fn main() {
assert_eq!(has_mut_vec(vec!(1, 2, 3)), 6);
}
| {
want_slice(&v)
} | identifier_body |
borrowck-mut-vec-as-imm-slice.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 ... | (v: &[isize]) -> isize {
let mut sum = 0;
for i in v { sum += *i; }
sum
}
fn has_mut_vec(v: Vec<isize> ) -> isize {
want_slice(&v)
}
pub fn main() {
assert_eq!(has_mut_vec(vec!(1, 2, 3)), 6);
}
| want_slice | identifier_name |
borrowck-mut-vec-as-imm-slice.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 ... | }
pub fn main() {
assert_eq!(has_mut_vec(vec!(1, 2, 3)), 6);
} |
fn has_mut_vec(v: Vec<isize> ) -> isize {
want_slice(&v) | random_line_split |
regions-fn-bound.rs | // xfail-test
// xfail'd because the first error does not show up.
// 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.apa... | <T>(_x: &'x T, _y: &'y T, _z: &'z T) {
// Here, x, y, and z are free. Other letters
// are bound. Note that the arrangement
// subtype::<T1>(of::<T2>()) will typecheck
// iff T1 <: T2.
// should be the default:
subtype::<'static ||>(of::<||>());
subtype::<||>(of::<'static ||>());
//
... | test_fn | identifier_name |
regions-fn-bound.rs | // xfail-test
// xfail'd because the first error does not show up.
// 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.apa... | {
// Here, x, y, and z are free. Other letters
// are bound. Note that the arrangement
// subtype::<T1>(of::<T2>()) will typecheck
// iff T1 <: T2.
// should be the default:
subtype::<'static ||>(of::<||>());
subtype::<||>(of::<'static ||>());
//
subtype::<'x ||>(of::<||>()); ... | identifier_body | |
regions-fn-bound.rs | // xfail-test
// xfail'd because the first error does not show up.
// 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.apa... | // subtype::<T1>(of::<T2>()) will typecheck
// iff T1 <: T2.
// should be the default:
subtype::<'static ||>(of::<||>());
subtype::<||>(of::<'static ||>());
//
subtype::<'x ||>(of::<||>()); //~ ERROR mismatched types
subtype::<'x ||>(of::<'y ||>()); //~ ERROR mismatched types
... | // are bound. Note that the arrangement | random_line_split |
lib.rs | // DO NOT EDIT!
// This file was generated automatically from'src/mako/api/lib.rs.mako'
// DO NOT EDIT!
//! This documentation was generated from *coordinate* crate version *0.1.8+20141215*, where *20141215* is the exact revision of the *coordinate:v1* schema built by the [mako](http://www.makotemplates.org/) code gen... | //! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
//! // retrieve them from storage.
//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
//! ... | //! // unless you replace `None` with the desired Flow. | random_line_split |
echoserver.rs | use std::net::{TcpListener, TcpStream};
use std::thread;
// traits
use std::io::Read;
use std::io::Write;
fn | (mut stream: TcpStream) {
let mut buf;
loop {
// clear out the buffer so we don't send garbage
buf = [0; 512];
let _ = match stream.read(&mut buf) {
Err(e) => panic!("Got an error: {}", e),
Ok(count) => {
if count == 0 {
// we'v... | handle_client | identifier_name |
echoserver.rs | use std::net::{TcpListener, TcpStream};
use std::thread;
// traits
use std::io::Read;
use std::io::Write;
fn handle_client(mut stream: TcpStream) {
let mut buf;
loop {
// clear out the buffer so we don't send garbage
buf = [0; 512];
let _ = match stream.read(&mut buf) {
Err... | Err(e) => { println!("failed: {}", e) }
Ok(stream) => {
thread::spawn(move || {
handle_client(stream)
});
}
}
}
} | fn main() {
let listener = TcpListener::bind("127.0.0.1:7777").unwrap();
println!("listen on 127.0.0.1:7777");
for stream in listener.incoming() {
match stream { | random_line_split |
echoserver.rs | use std::net::{TcpListener, TcpStream};
use std::thread;
// traits
use std::io::Read;
use std::io::Write;
fn handle_client(mut stream: TcpStream) {
let mut buf;
loop {
// clear out the buffer so we don't send garbage
buf = [0; 512];
let _ = match stream.read(&mut buf) {
Err... | {
let listener = TcpListener::bind("127.0.0.1:7777").unwrap();
println!("listen on 127.0.0.1:7777");
for stream in listener.incoming() {
match stream {
Err(e) => { println!("failed: {}", e) }
Ok(stream) => {
thread::spawn(move || {
handle_c... | identifier_body | |
main.rs | //!
//! Edgequest Season 2
//!
//! Edgequest is a roguelike that probably won't ever be finished due to the scope
//! of things I want to be in the game, but so far it's a pretty great tech demo of
//! interesting modern roguelike mechanics.
//!
//! The overarching design philosophy of edgequest is to treat the smal... | {
core::Engine::new().play();
} | identifier_body | |
main.rs | //!
//! Edgequest Season 2
//!
//! Edgequest is a roguelike that probably won't ever be finished due to the scope
//! of things I want to be in the game, but so far it's a pretty great tech demo of
//! interesting modern roguelike mechanics.
//!
//! The overarching design philosophy of edgequest is to treat the smal... | () {
core::Engine::new().play();
} | main | identifier_name |
main.rs | //!
//! Edgequest Season 2
//!
//! Edgequest is a roguelike that probably won't ever be finished due to the scope
//! of things I want to be in the game, but so far it's a pretty great tech demo of
//! interesting modern roguelike mechanics.
//!
//! The overarching design philosophy of edgequest is to treat the smal... | } |
// Defer to game to start playing.
fn main() {
core::Engine::new().play(); | random_line_split |
binop.rs | use std::ops::{Add, Sub, Mul, Div};
/// Binary numeric operators
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum BinOp {
/// a + b
Add,
/// a - b
Sub,
/// b - a
SubSwap,
/// a * b
Mul,
/// a / b
Div,
/// b / a
DivSwap,
}
impl BinOp {
/// a `op` b
pub fn ev... |
/// ((a `op` b) `op.invert()` b) == a
pub fn invert(&self) -> BinOp {
match *self {
BinOp::Add => BinOp::Sub,
BinOp::Sub => BinOp::Add,
BinOp::SubSwap => BinOp::SubSwap,
BinOp::Mul => BinOp::Div,
BinOp::Div => BinOp::Mul,
... | {
match *self {
BinOp::Add => BinOp::Add,
BinOp::Sub => BinOp::SubSwap,
BinOp::SubSwap => BinOp::Sub,
BinOp::Mul => BinOp::Mul,
BinOp::Div => BinOp::DivSwap,
BinOp::DivSwap => BinOp::Div,
}
} | identifier_body |
binop.rs | use std::ops::{Add, Sub, Mul, Div};
/// Binary numeric operators
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum | {
/// a + b
Add,
/// a - b
Sub,
/// b - a
SubSwap,
/// a * b
Mul,
/// a / b
Div,
/// b / a
DivSwap,
}
impl BinOp {
/// a `op` b
pub fn eval<A, B, C>(&self, a: A, b: B) -> C where
A: Add<B, Output=C>,
A: Sub<B, Output=C>,
B: Sub<A, Output=... | BinOp | identifier_name |
binop.rs | use std::ops::{Add, Sub, Mul, Div};
/// Binary numeric operators
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum BinOp {
/// a + b
Add,
/// a - b
Sub,
/// b - a
SubSwap,
/// a * b
Mul,
/// a / b
Div,
/// b / a
DivSwap,
}
impl BinOp {
/// a `op` b | pub fn eval<A, B, C>(&self, a: A, b: B) -> C where
A: Add<B, Output=C>,
A: Sub<B, Output=C>,
B: Sub<A, Output=C>,
A: Mul<B, Output=C>,
A: Div<B, Output=C>,
B: Div<A, Output=C> {
match *self {
BinOp::Add => a + b,
BinOp::Sub => a... | random_line_split | |
texture.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including wi... |
impl SdlTexture for Texture {
fn sdl_texture<'a>(&'a self) -> &'a sdl2::render::Texture {
&self.texture
}
} | // Separate so that it's not exported with the crate
pub trait SdlTexture {
fn sdl_texture<'a>(&'a self) -> &'a sdl2::render::Texture;
} | random_line_split |
texture.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including wi... | (sdl_texture: sdl2::render::Texture, width: u32, height: u32) -> Texture {
Texture {
width: width,
height: height,
texture: sdl_texture,
}
}
// Separate so that it's not exported with the crate
pub trait SdlTexture {
fn sdl_texture<'a>(&'a self) -> &'a sdl2::render::Texture;
}
impl... | create_texture | identifier_name |
irc.rs | use std::io::prelude::*;
use std::io::Error;
use std::net::TcpStream;
use std::str::FromStr;
use std::fs;
use std::fs::FileType;
use std::fs::DirEntry;
use std::path::Path;
use bufstream::BufStream;
use shared_library::*;
use libc::c_int;
use config::Config;
pub struct Irc
{
config: Config,
connected: bool,
... | (config: Config) -> Irc
{
return Irc { config: config, connected: false }
}
pub fn run(mut self: Self)
{
self.connected = false;
let paths = fs::read_dir("./").unwrap();
for path in paths {
let path_unwrapped = path.unwrap();
match path_unwrap... | new | identifier_name |
irc.rs | use std::io::prelude::*;
use std::io::Error;
use std::net::TcpStream;
use std::str::FromStr;
use std::fs;
use std::fs::FileType;
use std::fs::DirEntry;
use std::path::Path;
use bufstream::BufStream;
use shared_library::*;
use libc::c_int;
use config::Config;
pub struct Irc
{
config: Config,
connected: bool,
... | // top kek this line
match TcpStream::connect(&format!("{}:{}", self.config.server.hostname, self.config.server.port)[..]) {
Ok(tcp_stream) => {
info!("Connected");
self.connected = true;
let mut stream = BufStream::new(&tcp_stream);
... |
unsafe { (test.command)(); }
}
| random_line_split |
server.rs | extern crate websocket;
extern crate iron;
extern crate staticfile;
extern crate mount;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::{thread, time};
mod shared;
mod http_server;
mod websocket_server;
use http_server::start_http;
use websocket_server::start_ws;
use shared::*;
fn fake_emitter(sender: S... | thread::sleep(time::Duration::from_secs(1));
}
});
thread::spawn(move|| {
let mut clients: Vec<Sender<String>> = vec![];
loop {
match receiver.recv() {
Ok(CoordinatorMessage::Timeout()) => { println!("Time to send some data!") }
Ok(... | random_line_split | |
server.rs | extern crate websocket;
extern crate iron;
extern crate staticfile;
extern crate mount;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::{thread, time};
mod shared;
mod http_server;
mod websocket_server;
use http_server::start_http;
use websocket_server::start_ws;
use shared::*;
fn fake_emitter(sender: S... | {
let (to_coord, coord_receiver) = channel::<CoordinatorMessage>();
fake_emitter(to_coord.clone(), coord_receiver);
let _listening = start_http("0.0.0.0:8080");
start_ws("0.0.0.0:8081", to_coord);
} | identifier_body | |
server.rs | extern crate websocket;
extern crate iron;
extern crate staticfile;
extern crate mount;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::{thread, time};
mod shared;
mod http_server;
mod websocket_server;
use http_server::start_http;
use websocket_server::start_ws;
use shared::*;
fn fake_emitter(sender: S... |
Ok(CoordinatorMessage::NewClient(s)) => {
println!("A new client!");
clients.push(s);
}
Err(e) => { panic!("An error occured: {:?}", e)}
}
}
});
}
fn main() {
let (to_coord, coord_receiver) = chann... | { println!("Time to send some data!") } | conditional_block |
server.rs | extern crate websocket;
extern crate iron;
extern crate staticfile;
extern crate mount;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::{thread, time};
mod shared;
mod http_server;
mod websocket_server;
use http_server::start_http;
use websocket_server::start_ws;
use shared::*;
fn | (sender: Sender<CoordinatorMessage>, receiver: Receiver<CoordinatorMessage>) {
thread::spawn(move|| {
loop {
sender.send(CoordinatorMessage::Timeout()).unwrap();
thread::sleep(time::Duration::from_secs(1));
}
});
thread::spawn(move|| {
let mut clients: Vec<Se... | fake_emitter | identifier_name |
uievent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... |
pub fn new_uninitialized(window: &Window) -> DomRoot<UIEvent> {
reflect_dom_object(box UIEvent::new_inherited(),
window,
UIEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: DOMString,
can_bubble: EventBubble... | } | random_line_split |
uievent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... | (&self) -> i32 {
self.detail.get()
}
// https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent
fn InitUIEvent(&self,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Option<&Window>,
detail: ... | Detail | identifier_name |
uievent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... |
// https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent
fn InitUIEvent(&self,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Option<&Window>,
detail: i32) {
let event = self.upcast::<Event>(... | {
self.detail.get()
} | identifier_body |
uievent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... |
event.init_event(Atom::from(type_), can_bubble, cancelable);
self.view.set(view);
self.detail.set(detail);
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
return;
} | conditional_block |
wtypesbase.rs | // Copyright © 2016-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,... | }}
STRUCT!{struct BYTE_BLOB {
clSize: ULONG,
abData: [byte; 1],
}}
pub type UP_BYTE_BLOB = *mut BYTE_BLOB;
STRUCT!{struct WORD_BLOB {
clSize: ULONG,
asData: [c_ushort; 1],
}}
pub type UP_WORD_BLOB = *mut WORD_BLOB;
STRUCT!{struct DWORD_BLOB {
clSize: ULONG,
alData: [ULONG; 1],
}}
pub type UP_DWO... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.