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 |
|---|---|---|---|---|
connect_analysis.rs | // Copyright (c) 2016 srither-solver 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 co... | (graph: &[Vec<usize>], v: usize, visited: &mut [bool]) {
*visited.get_unchecked_mut(v) = true;
for &u in graph.get_unchecked(v) {
if *visited.get_unchecked(u) {
continue;
}
visit(graph, u, visited);
}
}
}
pub fn run(side_map: &mut SideMap... | visit | identifier_name |
lib.rs | extern crate chrono;
extern crate crowbook_text_processing;
extern crate iso8601;
#[macro_use] extern crate lazy_static;
extern crate num_traits;
extern crate pulldown_cmark;
extern crate regex;
extern crate yaml_rust;
use chrono::prelude::*;
use regex::Regex;
use self::capitalise::capitalise;
pub use self::metadata::... | (&self) -> String {
lazy_static! {
static ref EXT: Regex = Regex::new(r"\.[\w.]+$").unwrap();
}
let dateless = date::strip(&self.path);
String::from(EXT.replace_all(&dateless, ""))
}
pub fn slug(&self) -> String {
let slug_date = match self.is_page() {
... | extless_path | identifier_name |
lib.rs | extern crate chrono;
extern crate crowbook_text_processing;
extern crate iso8601;
#[macro_use] extern crate lazy_static;
extern crate num_traits;
extern crate pulldown_cmark;
extern crate regex;
extern crate yaml_rust;
use chrono::prelude::*;
use regex::Regex;
use self::capitalise::capitalise;
pub use self::metadata::... | &String::from(SPACED.replace_all(&self.extless_path(), " "))
)
}
}
pub fn render(&self) -> String {
markdown::render(&self.content)
}
} | random_line_split | |
request_headers.rs | use std::fmt::{self};
use header;
/// The `Access-Control-Request-Headers` request header,
/// part of [CORS](http://www.w3.org/TR/cors/).
///
/// > The `Access-Control-Request-Headers` header indicates which headers will
/// > be used in the actual request as part of the preflight request.
///
/// Spec: www.w3.org/T... | }
} | header::parsing::fmt_comma_delimited(f, parts.as_ref()) | random_line_split |
request_headers.rs | use std::fmt::{self};
use header;
/// The `Access-Control-Request-Headers` request header,
/// part of [CORS](http://www.w3.org/TR/cors/).
///
/// > The `Access-Control-Request-Headers` header indicates which headers will
/// > be used in the actual request as part of the preflight request.
///
/// Spec: www.w3.org/T... | () -> &'static str {
"Access-Control-Request-Headers"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlRequestHeaders> {
header::parsing::from_comma_delimited(raw).map(AccessControlRequestHeaders)
}
}
impl header::HeaderFormat for AccessControlRequestHeaders {
fn fmt_header(&s... | header_name | identifier_name |
request_headers.rs | use std::fmt::{self};
use header;
/// The `Access-Control-Request-Headers` request header,
/// part of [CORS](http://www.w3.org/TR/cors/).
///
/// > The `Access-Control-Request-Headers` header indicates which headers will
/// > be used in the actual request as part of the preflight request.
///
/// Spec: www.w3.org/T... |
}
impl header::HeaderFormat for AccessControlRequestHeaders {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
let AccessControlRequestHeaders(ref parts) = *self;
header::parsing::fmt_comma_delimited(f, parts.as_ref())
}
}
| {
header::parsing::from_comma_delimited(raw).map(AccessControlRequestHeaders)
} | identifier_body |
day_3.rs | pub use tdd_kata::string_calc_kata::iter_2::day_3::evaluate;
pub use expectest::prelude::be_ok;
describe! string_calculator {
it "should evaluate integer number" {
expect!(evaluate("324340")).to(be_ok().value(324340.0));
}
it "should evaluate float number" {
expect!(evaluate("2345054.054... | it "should evaluate division of two numbers" {
expect!(evaluate("4354÷2")).to(be_ok().value(2177.0));
}
} |
it "should evaluate multiplication of two numbers" {
expect!(evaluate("2435×2654")).to(be_ok().value(6462490.0));
}
| random_line_split |
glscene.rs | use std;
use gl::{
self, types::{GLfloat, GLuint, GLvoid},
};
use tutcommon::glutils;
// An array of 3 vectors which represents 3 vertices.
static G_VERTEX_BUFFER_DATA: [GLfloat; 9] = [-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0];
#[doc = "Moved out drawing GL stuff to avoid mess with the other code."]
#[der... | (&mut self) {
unsafe {
gl::DeleteProgram(self.program_id);
gl::DeleteBuffers(1, &self.vertex_buffer_id);
gl::DeleteVertexArrays(1, &self.vertex_array_id);
}
}
}
| drop | identifier_name |
glscene.rs | use std;
use gl::{
self, types::{GLfloat, GLuint, GLvoid},
};
use tutcommon::glutils;
// An array of 3 vectors which represents 3 vertices.
static G_VERTEX_BUFFER_DATA: [GLfloat; 9] = [-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0];
#[doc = "Moved out drawing GL stuff to avoid mess with the other code."]
#[der... |
// Create and compile our GLSL program from the shaders
let program_id = glutils::load_program(
"data/tut02/SimpleVertexShader.vertexshader",
"data/tut02/SimpleFragmentShader.fragmentshader",
);
let mut vertex_buffer_id = 0;
unsafe {
// Gene... | unsafe {
// create Vertex Array Object and set it as the current one:
gl::GenVertexArrays(1, &mut vertex_array_id);
gl::BindVertexArray(vertex_array_id);
} | random_line_split |
mod.rs | #![cfg(target_os = "ios")]
use GlAttributes;
use CreationError;
use PixelFormat;
use PixelFormatRequirements;
use ContextError;
pub use api::ios::*;
#[derive(Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;
pub struct HeadlessContext(i32);
impl HeadlessContext {
/// See the docs in the crate roo... |
}
unsafe impl Send for HeadlessContext {}
unsafe impl Sync for HeadlessContext {}
| {
unimplemented!();
} | identifier_body |
mod.rs | #![cfg(target_os = "ios")]
use GlAttributes;
use CreationError;
use PixelFormat;
use PixelFormatRequirements;
use ContextError;
pub use api::ios::*;
#[derive(Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;
pub struct HeadlessContext(i32);
impl HeadlessContext {
/// See the docs in the crate roo... | (&self) -> Result<(), ContextError> {
unimplemented!()
}
pub fn swap_buffers(&self) -> Result<(), ContextError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root fi... | make_current | identifier_name |
mod.rs | #![cfg(target_os = "ios")]
use GlAttributes;
use CreationError;
use PixelFormat;
use PixelFormatRequirements;
use ContextError;
pub use api::ios::*;
#[derive(Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;
pub struct HeadlessContext(i32);
impl HeadlessContext {
/// See the docs in the crate roo... | }
pub fn swap_buffers(&self) -> Result<(), ContextError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const (... | pub unsafe fn make_current(&self) -> Result<(), ContextError> {
unimplemented!() | random_line_split |
tinydb.rs | //! A "tiny database" and accompanying protocol
//!
//! This example shows the usage of shared state amongst all connected clients,
//! namely a database of key/value pairs. Each connected client can send a
//! series of GET/SET commands to query the current value of a key or set the
//! value of a key.
//!
//! This ex... | {
map: Mutex<HashMap<String, String>>,
}
/// Possible requests our clients can send us
enum Request {
Get { key: String },
Set { key: String, value: String },
}
/// Responses to the `Request` commands above
enum Response {
Value { key: String, value: String },
Set { key: String, value: String, pr... | Database | identifier_name |
tinydb.rs | //! A "tiny database" and accompanying protocol
//!
//! This example shows the usage of shared state amongst all connected clients,
//! namely a database of key/value pairs. Each connected client can send a
//! series of GET/SET commands to query the current value of a key or set the
//! value of a key.
//!
//! This ex... | None => return Err(format!("SET needs a value")),
};
Ok(Request::Set { key: key.to_string(), value: value.to_string() })
}
Some(cmd) => Err(format!("unknown command: {}", cmd)),
None => Err(format!("empty input")),
}
}
... | {
let mut parts = input.splitn(3, " ");
match parts.next() {
Some("GET") => {
let key = match parts.next() {
Some(key) => key,
None => return Err(format!("GET must be followed by a key")),
};
if parts.nex... | identifier_body |
tinydb.rs | //! A "tiny database" and accompanying protocol
//!
//! This example shows the usage of shared state amongst all connected clients,
//! namely a database of key/value pairs. Each connected client can send a
//! series of GET/SET commands to query the current value of a key or set the
//! value of a key.
//!
//! This ex... | //! GET FOOBAR
//! error: no key FOOBAR
//! SET FOOBAR my awesome string
//! set FOOBAR = `my awesome string`, previous: None
//! SET foo tokio
//! set foo = `tokio`, previous: Some("bar")
//! GET foo
//! foo = tokio
//!
//! Namely you can issue two forms of commands:
//!
//! * `GET $key... | //!
//!
//! $ cargo run --example connect 127.0.0.1:8080
//! GET foo
//! foo = bar | random_line_split |
object-lifetime-default-elision.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 ... | (&self) { }
}
struct SomeStruct<'a> {
r: Box<SomeTrait+'a>
}
fn deref<T>(ss: &T) -> T {
// produces the type of a deref without worrying about whether a
// move out would actually be legal
loop { }
}
fn load0<'a>(ss: &'a Box<SomeTrait>) -> Box<SomeTrait> {
// Under old rules, the fully elaborated... | dummy | identifier_name |
object-lifetime-default-elision.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 ... | //
// Under new rules the result is:
//
// for<'a> fn(&'a (SomeTrait+'a)) -> &'a (SomeTrait+'a)
//
// In both cases, returning `ss` is legal.
ss
}
fn load2<'a>(ss: &'a SomeTrait) -> &SomeTrait {
// Same as `load1` but with an explicit name thrown in for fun.
ss
}
fn load3<'a,'b>(... |
fn load1(ss: &SomeTrait) -> &SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a (SomeTrait+'b)) -> &'a (SomeTrait+'a) | random_line_split |
object-lifetime-default-elision.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 ... |
fn load2<'a>(ss: &'a SomeTrait) -> &SomeTrait {
// Same as `load1` but with an explicit name thrown in for fun.
ss
}
fn load3<'a,'b>(ss: &'a SomeTrait) -> &'b SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b,'c>fn(&'a (SomeTrait+'c)) -> &'b (SomeTr... | {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a (SomeTrait+'b)) -> &'a (SomeTrait+'a)
//
// Under new rules the result is:
//
// for<'a> fn(&'a (SomeTrait+'a)) -> &'a (SomeTrait+'a)
//
// In both cases, returning `ss` is legal.
ss
} | identifier_body |
formatter.rs | //! Primitives used by num_format and sub_modules.
//! never dealt with above (e.g. Sub Tokenizer never uses these)
use std::str::Chars;
use itertools::{PutBackN, put_back_n};
use cli;
use super::format_field::FormatField;
// contains the rough ingredients to final
// output for a number, organized together | pub pre_decimal: Option<String>,
pub post_decimal: Option<String>,
pub suffix: Option<String>,
}
impl Default for FormatPrimitive {
fn default() -> FormatPrimitive {
FormatPrimitive {
prefix: None,
pre_decimal: None,
post_decimal: None,
suffix: No... | // to allow for easy generalization of output manipulation
// (e.g. max number of digits after decimal)
pub struct FormatPrimitive {
pub prefix: Option<String>, | random_line_split |
formatter.rs | //! Primitives used by num_format and sub_modules.
//! never dealt with above (e.g. Sub Tokenizer never uses these)
use std::str::Chars;
use itertools::{PutBackN, put_back_n};
use cli;
use super::format_field::FormatField;
// contains the rough ingredients to final
// output for a number, organized together
// to all... | (pf_arg: &str) {
// important: keep println here not print
cli::err_msg(&format!("{}: value not completely converted", pf_arg))
}
| warn_incomplete_conv | identifier_name |
data.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/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElem... | (&self) -> bool {
!self.flags.intersects(ElementDataFlags::TRAVERSED_WITHOUT_STYLING |
ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE)
}
/// Measures memory usage.
#[cfg(feature = "gecko")]
pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usi... | safe_for_cousin_sharing | identifier_name |
data.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/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElem... |
}
// Manually implement `Clone` here because the derived impl of `Clone` for
// array types assumes the value inside is `Copy`.
impl Clone for EagerPseudoArray {
fn clone(&self) -> Self {
let mut clone = Self::default();
for i in 0..EAGER_PSEUDO_COUNT {
clone[i] = self.0[i].clone();
... | {
&mut self.0
} | identifier_body |
data.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/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElem... |
if!self.has_styles() {
return RestyleKind::MatchAndCascade;
}
if self.hint.match_self() {
return RestyleKind::MatchAndCascade;
}
if self.hint.has_replacements() {
debug_assert!(!self.hint.has_animation_hint(),
"Ani... | {
return self.restyle_kind_for_animation(shared_context);
} | conditional_block |
data.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/. */
//! Per-node data used in style calculation.
use context::{SharedStyleContext, StackLimitChecker};
use dom::TElem... | /// We use this to make sure the cascade of off-main thread animations is correct.
/// Note: Ignore custom properties for now because we only support opacity and transform
/// properties for animations running on compositor. Actually, we only care about opacity
/// and transform for now, but... | random_line_split | |
mod.rs | use std::cmp;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::ops::{Add, Div, Mul, Rem, Sub};
use std::path::Path;
use std::{error::Error, fmt::Display};
use chainstate::stacks::events::{StacksTransactionReceipt, TransactionOrigin};
use chainstate::stacks::{StacksBlock, TransactionPayload};
use ru... | Ok(())
}
fn get_rate_estimates(&self) -> Result<FeeRateEstimate, EstimatorError> {
Err(EstimatorError::NoEstimateAvailable)
}
}
/// This estimator always returns a unit estimate in all dimensions.
/// This can be paired with the UnitMetric to cause block assembly to consider
/// *only* tra... | random_line_split | |
mod.rs | use std::cmp;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::ops::{Add, Div, Mul, Rem, Sub};
use std::path::Path;
use std::{error::Error, fmt::Display};
use chainstate::stacks::events::{StacksTransactionReceipt, TransactionOrigin};
use chainstate::stacks::{StacksBlock, TransactionPayload};
use ru... | (self) -> Vec<f64> {
vec![self.low, self.middle, self.high]
}
}
impl Mul<f64> for FeeRateEstimate {
type Output = FeeRateEstimate;
fn mul(self, rhs: f64) -> FeeRateEstimate {
FeeRateEstimate {
high: saturating_f64_math(self.high * rhs),
middle: saturating_f64_math(s... | to_vec | identifier_name |
mod.rs | use std::cmp;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::ops::{Add, Div, Mul, Rem, Sub};
use std::path::Path;
use std::{error::Error, fmt::Display};
use chainstate::stacks::events::{StacksTransactionReceipt, TransactionOrigin};
use chainstate::stacks::{StacksBlock, TransactionPayload};
use ru... |
}
/// Given a cost estimator and a scalar metric, estimate the fee rate for
/// the provided transaction
pub fn estimate_fee_rate<CE: CostEstimator +?Sized, CM: CostMetric +?Sized>(
tx: &StacksTransaction,
estimator: &CE,
metric: &CM,
block_limit: &ExecutionCost,
stacks_epoch_id: &StacksEpochId,
... | {
FeeRateEstimate {
high: saturating_f64_math(self.high + rhs.high),
middle: saturating_f64_math(self.middle + rhs.middle),
low: saturating_f64_math(self.low + rhs.low),
}
} | identifier_body |
options.rs | //! The user-configurable portion of the type checker.
use std::str;
use std::ascii::AsciiExt;
use std::path::{Path, PathBuf, MAIN_SEPARATOR};
use kailua_env::{Spanned, WithLoc};
use kailua_diag::{Report, Stop};
use kailua_syntax::Chunk;
/// Options for customizing the type checker.
///
/// All of those methods retu... | <S> {
source: S,
root: PathBuf,
package_path: Vec<Vec<u8>>,
package_cpath: Vec<Vec<u8>>,
}
impl<S: FsSource> FsOptions<S> {
pub fn new(source: S, root: PathBuf) -> FsOptions<S> {
FsOptions {
source: source,
root: root,
// by default, local files only
... | FsOptions | identifier_name |
options.rs | //! The user-configurable portion of the type checker.
use std::str;
use std::ascii::AsciiExt;
use std::path::{Path, PathBuf, MAIN_SEPARATOR};
use kailua_env::{Spanned, WithLoc};
use kailua_diag::{Report, Stop};
use kailua_syntax::Chunk;
/// Options for customizing the type checker.
///
/// All of those methods retu... |
}
}
/// An implementation of `Options` that loads from the file system.
///
/// The user should provide `FsSource`, which provides a simpler interface for this use case.
pub struct FsOptions<S> {
source: S,
root: PathBuf,
package_path: Vec<Vec<u8>>,
package_cpath: Vec<Vec<u8>>,
}
impl<S: FsSource... | {
Err(None)
} | conditional_block |
options.rs | //! The user-configurable portion of the type checker.
use std::str;
use std::ascii::AsciiExt;
use std::path::{Path, PathBuf, MAIN_SEPARATOR};
use kailua_env::{Spanned, WithLoc};
use kailua_diag::{Report, Stop};
use kailua_syntax::Chunk;
/// Options for customizing the type checker.
///
/// All of those methods retu... | return Ok(chunk);
}
if let Some(chunk) = self.search_file(path, &self.package_path, b"", report)? {
return Ok(chunk);
}
if let Some(chunk) = self.search_file(path, &self.package_cpath, b".kailua", report)? {
return Ok(chunk);
}
// avoid... | report: &Report) -> Result<Chunk, Option<Stop>> {
if let Some(chunk) = self.search_file(path, &self.package_path, b".kailua", report)? { | random_line_split |
options.rs | //! The user-configurable portion of the type checker.
use std::str;
use std::ascii::AsciiExt;
use std::path::{Path, PathBuf, MAIN_SEPARATOR};
use kailua_env::{Spanned, WithLoc};
use kailua_diag::{Report, Stop};
use kailua_syntax::Chunk;
/// Options for customizing the type checker.
///
/// All of those methods retu... |
fn search_file(&self, path: Spanned<&[u8]>, search_paths: &[Vec<u8>], suffix: &[u8],
report: &Report) -> Result<Option<Chunk>, Option<Stop>> {
for template in search_paths {
let mut newpath = Vec::new();
let mut newpathdot = Vec::new();
for (i, e) in ... | {
FsOptions {
source: source,
root: root,
// by default, local files only
package_path: vec![b"?.lua".to_vec()],
package_cpath: vec![],
}
} | identifier_body |
day10.rs | use itertools::Itertools;
fn day10(input: &str) -> (usize, usize) {
let mut i = 1;
let mut next = String::from(input);
let mut part1 = 0;
let mut part2 = 0;
loop {
// worst case size is double the digits
let mut buf = String::with_capacity(next.len() * 2);
for (number, list)... | i += 1;
if i == 51 {
break;
}
}
return (part1, part2);
}
pub fn main() {
let (part1, part2) = day10("3113322113");
println!("Part 1: {}\nPart 2: {}", part1, part2);
}
#[test]
fn test() {
let (part1, part2) = day10("3113322113");
assert_eq!(part1, 329356);
... | if i == 50 {
part2 = next.len();
} | random_line_split |
day10.rs | use itertools::Itertools;
fn | (input: &str) -> (usize, usize) {
let mut i = 1;
let mut next = String::from(input);
let mut part1 = 0;
let mut part2 = 0;
loop {
// worst case size is double the digits
let mut buf = String::with_capacity(next.len() * 2);
for (number, list) in next.chars().group_by(|&x| x) {... | day10 | identifier_name |
day10.rs | use itertools::Itertools;
fn day10(input: &str) -> (usize, usize) {
let mut i = 1;
let mut next = String::from(input);
let mut part1 = 0;
let mut part2 = 0;
loop {
// worst case size is double the digits
let mut buf = String::with_capacity(next.len() * 2);
for (number, list)... |
}
return (part1, part2);
}
pub fn main() {
let (part1, part2) = day10("3113322113");
println!("Part 1: {}\nPart 2: {}", part1, part2);
}
#[test]
fn test() {
let (part1, part2) = day10("3113322113");
assert_eq!(part1, 329356);
assert_eq!(part2, 4666278);
}
| {
break;
} | conditional_block |
day10.rs | use itertools::Itertools;
fn day10(input: &str) -> (usize, usize) | if i == 51 {
break;
}
}
return (part1, part2);
}
pub fn main() {
let (part1, part2) = day10("3113322113");
println!("Part 1: {}\nPart 2: {}", part1, part2);
}
#[test]
fn test() {
let (part1, part2) = day10("3113322113");
assert_eq!(part1, 329356);
assert_eq!(pa... | {
let mut i = 1;
let mut next = String::from(input);
let mut part1 = 0;
let mut part2 = 0;
loop {
// worst case size is double the digits
let mut buf = String::with_capacity(next.len() * 2);
for (number, list) in next.chars().group_by(|&x| x) {
buf.push_str(&list.... | identifier_body |
posix.rs | #![allow(dead_code)]
// New rule: only posix.rs gets to use libc.
extern crate libc;
use std::process::exit;
use std::mem;
use std::ops::Drop;
use std::io;
use std::io::Result;
use std::io::Read;
use std::io::Write;
use std::io::Error;
use std::io::ErrorKind;
use std::fmt;
use std::os::unix::io::AsRawFd;
use st... | (&mut self, buf: &mut [u8]) -> Result<usize> {
self.0.read(buf)
}
}
impl Write for WritePipe {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> Result<()> {
self.0.flush()
}
}
/// Initialize the shell in a POSIX-pleasing way
pub... | read | identifier_name |
posix.rs | #![allow(dead_code)]
// New rule: only posix.rs gets to use libc.
extern crate libc;
use std::process::exit;
use std::mem;
use std::ops::Drop;
use std::io;
use std::io::Result;
use std::io::Read;
use std::io::Write;
use std::io::Error;
use std::io::ErrorKind;
use std::fmt;
use std::os::unix::io::AsRawFd;
use st... | }
Error::last_os_error()
} | pub fn execv(cmd: *const i8, argv: *const *const i8) -> Error {
unsafe {
libc::execv(cmd, argv); | random_line_split |
posix.rs | #![allow(dead_code)]
// New rule: only posix.rs gets to use libc.
extern crate libc;
use std::process::exit;
use std::mem;
use std::ops::Drop;
use std::io;
use std::io::Result;
use std::io::Read;
use std::io::Write;
use std::io::Error;
use std::io::ErrorKind;
use std::fmt;
use std::os::unix::io::AsRawFd;
use st... |
}
/// Puts a process into a process group.
/// If pid is None, puts the calling process into the process group.
/// If pgid is None, creates a new process group with pgid = pid.
///
/// Returns, upon success, the Pgid into which this process was put.
///
/// (Even if both pid and pgid is None, returns a nonzero Pgid ... | {
let pid = Some(Pid(c_pid));
if inter {
try!(put_into_pgrp(pid, pgid));
try!(set_signal_ignore(false));
}
Ok(pid)
} | conditional_block |
posix.rs | #![allow(dead_code)]
// New rule: only posix.rs gets to use libc.
extern crate libc;
use std::process::exit;
use std::mem;
use std::ops::Drop;
use std::io;
use std::io::Result;
use std::io::Read;
use std::io::Write;
use std::io::Error;
use std::io::ErrorKind;
use std::fmt;
use std::os::unix::io::AsRawFd;
use st... |
pub fn set_signal_ignore(ignore: bool) -> Result<()> {
macro_rules! stry {
($e:expr) => {{
let res = $e;
if res == libc::SIG_ERR {
return Err(Error::last_os_error());
}
res
}}
}
let action = if ignore {
libc::SIG_IGN
... | {
unsafe {
etry!(libc::dup2(dest, src));
}
Ok(())
} | identifier_body |
unsafety.rs | //! Unsafety checker: every impl either implements a trait defined in this
//! crate or pertains to a type defined in this crate.
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::Unsafety;
use rustc_middle::ty::TyCtxt;
pub fn check(tcx: TyCtxt<'_>)... | (&mut self, _trait_item: &hir::TraitItem<'_>) {}
fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}
}
| visit_trait_item | identifier_name |
unsafety.rs | //! Unsafety checker: every impl either implements a trait defined in this
//! crate or pertains to a type defined in this crate.
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::Unsafety;
use rustc_middle::ty::TyCtxt;
pub fn check(tcx: TyCtxt<'_>)... |
(_, _, Unsafety::Unsafe, hir::ImplPolarity::Negative(_)) => {
// Reported in AST validation
self.tcx.sess.delay_span_bug(item.span, "unsafe negative impl");
}
(_, _, Unsafety::Normal, hir::ImplPolarity::Negative(_))
... | {
struct_span_err!(
self.tcx.sess,
item.span,
E0569,
"requires an `unsafe impl` declaration due to `#[{}]` attribute",
attr_name
)
.emit();
... | conditional_block |
unsafety.rs | //! Unsafety checker: every impl either implements a trait defined in this
//! crate or pertains to a type defined in this crate.
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::Unsafety;
use rustc_middle::ty::TyCtxt;
pub fn check(tcx: TyCtxt<'_>)... | self.tcx.sess,
item.span,
E0200,
"the trait `{}` requires an `unsafe impl` declaration",
trait_ref.print_only_trait_path()
)
.emit();
}
... | {
if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id) {
let trait_def = self.tcx.trait_def(trait_ref.def_id);
let unsafe_attr = impl_generics.and_then(|generics| {
generics.params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle")
});
... | identifier_body |
unsafety.rs | //! Unsafety checker: every impl either implements a trait defined in this
//! crate or pertains to a type defined in this crate.
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::itemlikevisit::ItemLikeVisitor;
use rustc_hir::Unsafety;
use rustc_middle::ty::TyCtxt;
pub fn check(tcx: TyCtxt<'_>)... | item.span,
E0199,
"implementing the trait `{}` is not unsafe",
trait_ref.print_only_trait_path()
)
.emit();
}
(Unsafety::Unsafe, _, Unsafety::Normal, hi... | struct_span_err!(
self.tcx.sess, | random_line_split |
check_loop.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 ... | {
Normal, Loop, Closure
}
struct CheckLoopVisitor<'a> {
tcx: &'a ty::ctxt,
}
pub fn check_crate(tcx: &ty::ctxt, krate: &ast::Crate) {
visit::walk_crate(&mut CheckLoopVisitor { tcx: tcx }, krate, Normal)
}
impl<'a> Visitor<Context> for CheckLoopVisitor<'a> {
fn visit_item(&mut self, i: &ast::Item, _c... | Context | identifier_name |
check_loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty;
use syntax::ast;
use syntax::codemap::Span;
use syntax::visit::Visitor;... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
check_loop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl<'a> Visitor<Context> for CheckLoopVisitor<'a> {
fn visit_item(&mut self, i: &ast::Item, _cx: Context) {
visit::walk_item(self, i, Normal);
}
fn visit_expr(&mut self, e: &ast::Expr, cx:Context) {
match e.node {
ast::ExprWhile(e, b) => {
self.visit_expr(e, c... | {
visit::walk_crate(&mut CheckLoopVisitor { tcx: tcx }, krate, Normal)
} | identifier_body |
mod.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
pub trait TokenStream<K, T>: Clone {
fn next(&self) -> Option<(Token<K, T>, Self)>;
}
#[derive(Derivative)]
#[derivative(Clone(bound = ""))]
pub struct VecTokenStream<K, T> {
tokens: Arc<Vec<Token<K, T>>>,
position: usize,
}
impl<K, T> VecTokenStream<K, T> {
pub fn from_into_iter<C: IntoIterator<Item = To... | {
Token { kind, value }
} | identifier_body |
mod.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use crate::grammar::ElemTypes;
pub mod earley;
... | // https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software | random_line_split |
mod.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | else {
assert_eq!(self.tokens.len(), self.position);
None
}
}
}
pub trait Parser<E: ElemTypes, T> {
fn parse<S: TokenStream<E::Term, T>>(
&self,
stream: S,
) -> anyhow::Result<tree::Node<E, T>>;
}
| {
Some((
self.tokens[self.position].clone(),
VecTokenStream {
tokens: self.tokens.clone(),
position: self.position + 1,
},
))
} | conditional_block |
mod.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (kind: K, value: T) -> Self {
Token { kind, value }
}
}
pub trait TokenStream<K, T>: Clone {
fn next(&self) -> Option<(Token<K, T>, Self)>;
}
#[derive(Derivative)]
#[derivative(Clone(bound = ""))]
pub struct VecTokenStream<K, T> {
tokens: Arc<Vec<Token<K, T>>>,
position: usize,
}
impl<K, T> VecTokenStrea... | new | identifier_name |
rdgsbase.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn rdgsbase_1() {
run_test(&Instruction { mnemonic: Mnemonic::RDGSBASE, operand1: Some(Direct(EBP)), operand2: None, opera... | () {
run_test(&Instruction { mnemonic: Mnemonic::RDGSBASE, operand1: Some(Direct(RCX)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 72, 15, 174, 201], OperandSize::Qword)
}
| rdgsbase_2 | identifier_name |
rdgsbase.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*; |
fn rdgsbase_2() {
run_test(&Instruction { mnemonic: Mnemonic::RDGSBASE, operand1: Some(Direct(RCX)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 72, 15, 174, 201], OperandSize::Qword)
} |
fn rdgsbase_1() {
run_test(&Instruction { mnemonic: Mnemonic::RDGSBASE, operand1: Some(Direct(EBP)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 15, 174, 205], OperandSize::Qword)
} | random_line_split |
rdgsbase.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn rdgsbase_1() |
fn rdgsbase_2() {
run_test(&Instruction { mnemonic: Mnemonic::RDGSBASE, operand1: Some(Direct(RCX)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 72, 15, 174, 201], OperandSize::Qword)
}
| {
run_test(&Instruction { mnemonic: Mnemonic::RDGSBASE, operand1: Some(Direct(EBP)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 15, 174, 205], OperandSize::Qword)
} | identifier_body |
macros.rs | macro_rules! consume_spaces {
($lexer:expr) => (
loop {
match $lexer.peek_next() {
Some(lexer::Token::Space) => (),
_ => break,
}
// Consume the actual space.
$lexer.next();
}
)
}
macro_rules! get_lex_token {
($... | v => {
let msg = format!("Expected: {:?}, found: {:?}.", stringify!($val), v);
return Err(
ParsingError::new(&msg).position(pos),
);
}
}
}
)
} | $val => (), | random_line_split |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use app_units::Au;
use context::{LayoutContext,... |
let layout_context = LayoutContext::new(shared_layout_context);
let root = flow_ref::deref_mut(root);
if opts::get().bubble_inline_sizes_separately {
let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context };
{
let root: &mut Flow = root;
root.trav... | }
} | random_line_split |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use app_units::Au;
use context::{LayoutContext,... | (flow: &mut Flow,
level: i32,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position);
for kid in flow::mut_base(flow).child_iter() {
let s... | doit | identifier_name |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use app_units::Au;
use context::{LayoutContext,... |
doit(flow_ref::deref_mut(root), 0, iterator, &ZERO_POINT);
}
| {
fn doit(flow: &mut Flow,
level: i32,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position);
for kid in flow::mut_base(flow).child_iter() {
... | identifier_body |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use app_units::Au;
use context::{LayoutContext,... | else {
*stacking_context_position
};
// FIXME(#2795): Get the real container size.
doit(kid, level + 1, iterator, &stacking_context_position);
}
}
doit(flow_ref::deref_mut(root), 0, iterator, &ZERO_POINT);
}
| {
let margin = Point2D::new(kid.as_block().fragment.margin.inline_start, Au(0));
*stacking_context_position + flow::base(kid).stacking_relative_position + margin
} | conditional_block |
lib.rs | //! This crate reads DVD subtitles in VobSub format. These are typically
//! stored as two files: an `*.idx` file summarizing the subtitles, and an | //! ```
//! extern crate image;
//! extern crate vobsub;
//!
//! let idx = vobsub::Index::open("../fixtures/example.idx").unwrap();
//! for sub in idx.subtitles() {
//! let sub = sub.unwrap();
//! println!("Time: {:0.3}-{:0.3}", sub.start_time(), sub.end_time());
//! println!("Always show: {:?}", sub.force(... | //! MPEG-2 Program Stream containing the actual subtitle packets.
//!
//! ## Example code
//! | random_line_split |
rate_limit.rs | metrics::HistogramVec;
use std::{cmp::min, collections::HashMap, fmt::Debug, hash::Hash, sync::Arc, time::Instant};
use tokio::time::Duration;
pub type SharedBucket = Arc<Mutex<Bucket>>;
const ONE_SEC: Duration = Duration::from_secs(1);
/// A generic token bucket filter
///
/// # Terms
/// ## Key
/// A `key` is an i... |
}
/// Returns `usize` of tokens allowed. May be less than requested.
/// For best effort, caller should return unused tokens with `add_tokens`
pub fn acquire_tokens(&mut self, requested: usize) -> Result<usize, Instant> {
// Skip over if we purposely have an open throttle
if!self.enab... | {
// Keep track of the requests we've throttled
self.throttled_in_period = self.throttled_in_period.saturating_add(requested);
Err(self.time_of_tokens_needed(requested))
} | conditional_block |
rate_limit.rs | <Mutex<Bucket>>;
const ONE_SEC: Duration = Duration::from_secs(1);
/// A generic token bucket filter
///
/// # Terms
/// ## Key
/// A `key` is an identifier of the item being rate limited
///
/// ## Token
/// A `token` is the smallest discrete value that we want to rate limit by. In a situation involving
/// network... | {
let key_to_keep = "don't gc";
let key_to_gc = "do gc";
let rate_limiter = TokenBucketRateLimiter::test(1, 1);
assert_num_keys(&rate_limiter, 0);
// Create a bucket to hold onto
let _bucket_arc = rate_limiter.bucket(key_to_keep);
assert_num_keys(&rate_limiter, 1... | identifier_body | |
rate_limit.rs | metrics::HistogramVec;
use std::{cmp::min, collections::HashMap, fmt::Debug, hash::Hash, sync::Arc, time::Instant};
use tokio::time::Duration;
pub type SharedBucket = Arc<Mutex<Bucket>>;
const ONE_SEC: Duration = Duration::from_secs(1);
/// A generic token bucket filter
///
/// # Terms
/// ## Key
/// A `key` is an i... | (&mut self, requested: usize) -> Result<(), Option<Instant>> {
// Skip over if we purposely have an open throttle
if!self.enabled || requested == 0 {
return Ok(());
}
// Refill if needed
self.refill();
if self.tokens >= requested {
self.deduct_to... | acquire_all_tokens | identifier_name |
rate_limit.rs | _metrics::HistogramVec;
use std::{cmp::min, collections::HashMap, fmt::Debug, hash::Hash, sync::Arc, time::Instant};
use tokio::time::Duration;
pub type SharedBucket = Arc<Mutex<Bucket>>;
const ONE_SEC: Duration = Duration::from_secs(1);
/// A generic token bucket filter
///
/// # Terms
/// ## Key
/// A `key` is an ... | ) -> SharedBucket {
// Attempt to do a weaker read lock first, followed by a write lock if it's missing
// For the common (read) case, there should be higher throughput
// Note: This read must happen in a separate block, to ensure the read unlock for the write
let maybe_bucket = { se... | key: Key,
bucket_create: F, | random_line_split |
surface.rs | // Copyright 2014-2015 Jonathan Eyolfson
use raw;
use super::Buffer;
pub struct Surface {
ptr: *mut raw::wl_surface
}
impl Surface {
pub unsafe fn from_ptr(ptr: *mut raw::wl_surface) -> Surface {
Surface { ptr: ptr }
}
pub unsafe fn to_ptr(&mut self) -> *mut raw::wl_surface {
self.pt... | (&mut self, buffer: &mut Buffer, x: i32, y: i32) {
unsafe {
raw::wl_surface_attach(self.ptr, buffer.to_ptr(), x, y);
}
}
pub fn commit(&mut self) {
unsafe {
raw::wl_surface_commit(self.ptr);
}
}
}
impl Drop for Surface {
fn drop(&mut self) {
... | attach | identifier_name |
surface.rs | // Copyright 2014-2015 Jonathan Eyolfson
use raw;
use super::Buffer;
pub struct Surface {
ptr: *mut raw::wl_surface
}
impl Surface {
pub unsafe fn from_ptr(ptr: *mut raw::wl_surface) -> Surface |
pub unsafe fn to_ptr(&mut self) -> *mut raw::wl_surface {
self.ptr
}
pub fn attach(&mut self, buffer: &mut Buffer, x: i32, y: i32) {
unsafe {
raw::wl_surface_attach(self.ptr, buffer.to_ptr(), x, y);
}
}
pub fn commit(&mut self) {
unsafe {
raw:... | {
Surface { ptr: ptr }
} | identifier_body |
surface.rs |
use super::Buffer;
pub struct Surface {
ptr: *mut raw::wl_surface
}
impl Surface {
pub unsafe fn from_ptr(ptr: *mut raw::wl_surface) -> Surface {
Surface { ptr: ptr }
}
pub unsafe fn to_ptr(&mut self) -> *mut raw::wl_surface {
self.ptr
}
pub fn attach(&mut self, buffer: &mut B... | // Copyright 2014-2015 Jonathan Eyolfson
use raw; | random_line_split | |
tyencode.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... |
ty::ty_err => {
mywrite!(w, "e");
}
}
}
fn enc_fn_style(w: &mut MemWriter, p: FnStyle) {
match p {
NormalFn => mywrite!(w, "n"),
UnsafeFn => mywrite!(w, "u"),
}
}
fn enc_abi(w: &mut MemWriter, abi: Abi) {
mywrite!(w, "[");
mywrite!(w, "{}", abi.name());... | {
mywrite!(w, "k{}", (cx.ds)(def));
} | conditional_block |
tyencode.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... |
fn enc_sty(w: &mut MemWriter, cx: &ctxt, st: &ty::sty) {
match *st {
ty::ty_nil => mywrite!(w, "n"),
ty::ty_bot => mywrite!(w, "z"),
ty::ty_bool => mywrite!(w, "b"),
ty::ty_char => mywrite!(w, "c"),
ty::ty_int(t) => {
match t {
TyI => mywrite!(w,... | {
match s {
ty::UniqTraitStore => mywrite!(w, "~"),
ty::RegionTraitStore(re, m) => {
mywrite!(w, "&");
enc_region(w, cx, re);
enc_mutability(w, m);
}
}
} | identifier_body |
tyencode.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... | mywrite!(w, "t");
}
ty::ReEmpty => {
mywrite!(w, "e");
}
ty::ReInfer(_) => {
// these should not crop up after typeck
cx.diag.handler().bug("cannot encode region variables");
}
}
}
fn enc_bound_region(w: &mut MemWriter, cx: &ct... | }
ty::ReStatic => { | random_line_split |
tyencode.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... | (w: &mut MemWriter, cx: &ctxt, s: ty::TraitStore) {
match s {
ty::UniqTraitStore => mywrite!(w, "~"),
ty::RegionTraitStore(re, m) => {
mywrite!(w, "&");
enc_region(w, cx, re);
enc_mutability(w, m);
}
}
}
fn enc_sty(w: &mut MemWriter, cx: &ctxt, st: &t... | enc_trait_store | identifier_name |
ffi.rs | //! Windows-specific extensions to the primitives in the `std::ffi` module.
//!
//! # Overview
//!
//! For historical reasons, the Windows API uses a form of potentially
//! ill-formed UTF-16 encoding for strings. Specifically, the 16-bit
//! code units in Windows strings may contain [isolated surrogate code
//! points... | (wide: &[u16]) -> OsString {
FromInner::from_inner(Buf { inner: Wtf8Buf::from_wide(wide) })
}
}
/// Windows-specific extensions to [`OsStr`].
///
/// This trait is sealed: it cannot be implemented outside the standard library.
/// This is so that future additional methods are not breaking changes.
#[stable... | from_wide | identifier_name |
ffi.rs | //! Windows-specific extensions to the primitives in the `std::ffi` module.
//!
//! # Overview
//!
//! For historical reasons, the Windows API uses a form of potentially
//! ill-formed UTF-16 encoding for strings. Specifically, the 16-bit
//! code units in Windows strings may contain [isolated surrogate code
//! points... |
}
| {
self.as_inner().inner.encode_wide()
} | identifier_body |
ffi.rs | //! Windows-specific extensions to the primitives in the `std::ffi` module.
//!
//! # Overview
//!
//! For historical reasons, the Windows API uses a form of potentially
//! ill-formed UTF-16 encoding for strings. Specifically, the 16-bit
//! code units in Windows strings may contain [isolated surrogate code
//! points... | ///
/// let string = OsString::from_wide(&source[..]);
///
/// let result: Vec<u16> = string.encode_wide().collect();
/// assert_eq!(&source[..], &result[..]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn encode_wide(&self) -> EncodeWide<'_>;
}
#[stable(feature = "rust1", si... | random_line_split | |
lex_b_tree_sets_length_range.rs | use itertools::Itertools;
use malachite_base::bools::exhaustive::exhaustive_bools;
use malachite_base::nevers::nevers;
use malachite_base::sets::exhaustive::lex_b_tree_sets_length_range;
use malachite_base::tuples::exhaustive::exhaustive_units;
use std::collections::BTreeSet;
use std::fmt::Debug;
fn lex_b_tree_sets_le... | () {
lex_b_tree_sets_length_range_small_helper(0, 5, nevers(), 1, &[btreeset! {}]);
lex_b_tree_sets_length_range_small_helper(6, 10, nevers(), 0, &[]);
lex_b_tree_sets_length_range_small_helper(
0,
5,
exhaustive_units(),
2,
&[btreeset! {}, btreeset! {()}],
);
... | test_lex_b_tree_sets_length_range | identifier_name |
lex_b_tree_sets_length_range.rs | use itertools::Itertools;
use malachite_base::bools::exhaustive::exhaustive_bools;
use malachite_base::nevers::nevers;
use malachite_base::sets::exhaustive::lex_b_tree_sets_length_range;
use malachite_base::tuples::exhaustive::exhaustive_units;
use std::collections::BTreeSet;
use std::fmt::Debug;
fn lex_b_tree_sets_le... |
#[test]
fn test_lex_b_tree_sets_length_range() {
lex_b_tree_sets_length_range_small_helper(0, 5, nevers(), 1, &[btreeset! {}]);
lex_b_tree_sets_length_range_small_helper(6, 10, nevers(), 0, &[]);
lex_b_tree_sets_length_range_small_helper(
0,
5,
exhaustive_units(),
2,
... | {
let xss = lex_b_tree_sets_length_range(a, b, xs);
let xss_prefix = xss.clone().take(20).collect_vec();
assert_eq!(xss_prefix.into_iter().collect_vec().as_slice(), out);
assert_eq!(xss.count(), out_len);
} | identifier_body |
lex_b_tree_sets_length_range.rs | use itertools::Itertools;
use malachite_base::bools::exhaustive::exhaustive_bools;
use malachite_base::nevers::nevers;
use malachite_base::sets::exhaustive::lex_b_tree_sets_length_range; | use malachite_base::tuples::exhaustive::exhaustive_units;
use std::collections::BTreeSet;
use std::fmt::Debug;
fn lex_b_tree_sets_length_range_small_helper<I: Clone + Iterator>(
a: u64,
b: u64,
xs: I,
out_len: usize,
out: &[BTreeSet<I::Item>],
) where
I::Item: Clone + Debug + Eq + Ord,
{
le... | random_line_split | |
lib.rs | //! # mdBook
//!
//! **mdBook** is similar to Gitbook but implemented in Rust.
//! It offers a command line interface, but can also be used as a regular crate.
//!
//! This is the API doc, but you can find a [less "low-level" documentation here](../index.html) that
//! contains information about the command line tool, ... | //! ```
//! This function creates all the directories in a given path if they do not exist
//!
//! Make sure to take a look at it.
extern crate serde;
extern crate serde_json;
extern crate handlebars;
extern crate pulldown_cmark;
#[macro_use] extern crate log;
pub mod book;
mod parse;
pub mod renderer;
pub mod theme;... | //! ```ignore
//! utils::fs::create_path(path: &Path) | random_line_split |
stream_engine.rs | use std::sync::mpsc::channel;
use std::thread::Thread;
use consts::ErrorCode;
use msg::Msg;
use options::Options;
use result::{ZmqError, ZmqResult};
use socket_base::SocketMessage;
use v2_encoder::V2Encoder;
use v2_decoder::V2Decoder;
use std::old_io::extensions;
use std::old_io::{TcpStream, Reader};
use std::sync::{R... | }
impl StreamEngine {
fn run(&mut self) -> ZmqResult<()> {
info!("Connection is made: {} -> {}", self.stream.socket_name(), self.stream.peer_name());
// prepare task for bufferring outgoing bytes
let (bytes_tx, bytes_rx) = channel();
let (waiter_tx, waiter_rx) = channel();
... | stream: TcpStream,
options: Arc<RwLock<Options>>,
// a sender to unblock all receivers on drop
_death_notifier: Option<Sender<u8>>, | random_line_split |
stream_engine.rs | use std::sync::mpsc::channel;
use std::thread::Thread;
use consts::ErrorCode;
use msg::Msg;
use options::Options;
use result::{ZmqError, ZmqResult};
use socket_base::SocketMessage;
use v2_encoder::V2Encoder;
use v2_decoder::V2Decoder;
use std::old_io::extensions;
use std::old_io::{TcpStream, Reader};
use std::sync::{R... |
let (decoder, encoder) = try!(self.handshake(bytes_tx));
let _ = waiter_rx.recv_opt(); // wait until all outgoing handshake bytes are committed
debug!("Handshake is done: {} -> {}", self.stream.socket_name(), self.stream.peer_name());
// prepare task for sending Msg objects
le... | {
return Err(ZmqError::new(ErrorCode::EIOERROR, "Connection closed"));
} | conditional_block |
stream_engine.rs | use std::sync::mpsc::channel;
use std::thread::Thread;
use consts::ErrorCode;
use msg::Msg;
use options::Options;
use result::{ZmqError, ZmqResult};
use socket_base::SocketMessage;
use v2_encoder::V2Encoder;
use v2_decoder::V2Decoder;
use std::old_io::extensions;
use std::old_io::{TcpStream, Reader};
use std::sync::{R... |
}
| {
Thread::spawn(move || {
let mut engine = StreamEngine {
chan_to_socket: chan,
stream: stream,
options: options,
_death_notifier: death_notifier,
};
let _ = engine.run();
});
} | identifier_body |
stream_engine.rs | use std::sync::mpsc::channel;
use std::thread::Thread;
use consts::ErrorCode;
use msg::Msg;
use options::Options;
use result::{ZmqError, ZmqResult};
use socket_base::SocketMessage;
use v2_encoder::V2Encoder;
use v2_decoder::V2Decoder;
use std::old_io::extensions;
use std::old_io::{TcpStream, Reader};
use std::sync::{R... | (&mut self) -> ZmqResult<()> {
info!("Connection is made: {} -> {}", self.stream.socket_name(), self.stream.peer_name());
// prepare task for bufferring outgoing bytes
let (bytes_tx, bytes_rx) = channel();
let (waiter_tx, waiter_rx) = channel();
let stream = self.stream.clone();... | run | identifier_name |
lib.rs | : Vec::new(),
compiler: None,
archiver: None,
cargo_metadata: true,
pic: None,
}
}
/// Add a directory to the `-I` or include path for headers
pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Config {
self.include_directories.push(dir... |
};
self.print(&format!("Detecting iOS SDK path for {}", sdk));
let sdk_path = self.cmd("xcrun")
.arg("--show-sdk-path")
.arg("--sdk")
.arg(sdk)
.stderr(Stdio::inherit())
.output()
.unwrap()
.stdout;
let sdk_p... | {
cmd.args.push(arch.into());
cmd.args.push("-mios-simulator-version-min=7.0".into());
"iphonesimulator"
} | conditional_block |
lib.rs | : Vec::new(),
compiler: None,
archiver: None,
cargo_metadata: true,
pic: None,
}
}
/// Add a directory to the `-I` or include path for headers
pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Config {
self.include_directories.push(dir... |
/// Configures the optimization level of the generated object files.
///
/// This option is automatically scraped from the `OPT_LEVEL` environment
/// variable by build scripts, so it's not required to call this function.
pub fn opt_level(&mut self, opt_level: u32) -> &mut Config {
self.op... | {
self.host = Some(host.to_string());
self
} | identifier_body |
lib.rs | c.compile(output)
}
impl Config {
/// Construct a new instance of a blank set of configuration.
///
/// This builder is finished with the `compile` function.
pub fn new() -> Config {
Config {
include_directories: Vec::new(),
definitions: Vec::new(),
objec... | random_line_split | ||
lib.rs | : Vec::new(),
compiler: None,
archiver: None,
cargo_metadata: true,
pic: None,
}
}
/// Add a directory to the `-I` or include path for headers
pub fn include<P: AsRef<Path>>(&mut self, dir: P) -> &mut Config {
self.include_directories.push(dir... | (&self, cmd: &mut Tool) {
enum ArchSpec {
Device(&'static str),
Simulator(&'static str),
}
let target = self.get_target();
let arch = target.split('-').nth(0).unwrap();
let arch = match arch {
"arm" | "armv7" | "thumbv7" => ArchSpec::Device("a... | ios_flags | identifier_name |
stream.rs | // Copyright 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-MIT or ... | task: None,
};
// When reading a TTY stream on windows, libuv will invoke alloc_cb
// immediately as part of the call to alloc_cb. What this means is that
// we must be ready for this to happen (by setting the data in the uv
// handle). In theory this otherwise doesn'... | random_line_split | |
stream.rs | // Copyright 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-MIT or ... | {
buf: Option<Buf>,
result: ssize_t,
task: Option<BlockedTask>,
}
struct WriteContext {
result: c_int,
task: Option<BlockedTask>,
}
impl StreamWatcher {
// Creates a new helper structure which should be then embedded into another
// watcher. This provides the generic read/write methods on... | ReadContext | identifier_name |
p073.rs | //! [Problem 73](https://projecteuler.net/problem=73) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn count_between(a: (u32, u32), b: (u32, u32), max_denom: u32) -> u32 |
fn solve() -> String { count_between((1, 3), (1, 2), 12000).to_string() }
problem!("7295372", solve);
#[cfg(test)]
mod tests {
#[test]
fn eight() { assert_eq!(3, super::count_between((1, 3), (1, 2), 8)); }
}
| {
if a.1 + b.1 > max_denom { return 0 }
let mid = (a.0 + b.0, a.1 + b.1);
count_between(a, mid, max_denom) + count_between(mid, b, max_denom) + 1
} | identifier_body |
p073.rs | //! [Problem 73](https://projecteuler.net/problem=73) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn count_between(a: (u32, u32), b: (u32, u32), max_denom: u32) -> u32 { | if a.1 + b.1 > max_denom { return 0 }
let mid = (a.0 + b.0, a.1 + b.1);
count_between(a, mid, max_denom) + count_between(mid, b, max_denom) + 1
}
fn solve() -> String { count_between((1, 3), (1, 2), 12000).to_string() }
problem!("7295372", solve);
#[cfg(test)]
mod tests {
#[test]
fn eight() { ass... | random_line_split | |
p073.rs | //! [Problem 73](https://projecteuler.net/problem=73) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn count_between(a: (u32, u32), b: (u32, u32), max_denom: u32) -> u32 {
if a.1 + ... |
let mid = (a.0 + b.0, a.1 + b.1);
count_between(a, mid, max_denom) + count_between(mid, b, max_denom) + 1
}
fn solve() -> String { count_between((1, 3), (1, 2), 12000).to_string() }
problem!("7295372", solve);
#[cfg(test)]
mod tests {
#[test]
fn eight() { assert_eq!(3, super::count_between((1, 3), (... | { return 0 } | conditional_block |
p073.rs | //! [Problem 73](https://projecteuler.net/problem=73) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn | (a: (u32, u32), b: (u32, u32), max_denom: u32) -> u32 {
if a.1 + b.1 > max_denom { return 0 }
let mid = (a.0 + b.0, a.1 + b.1);
count_between(a, mid, max_denom) + count_between(mid, b, max_denom) + 1
}
fn solve() -> String { count_between((1, 3), (1, 2), 12000).to_string() }
problem!("7295372", solve);
#... | count_between | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::cod... | (form: Option<&HTMLFormElement>, global: GlobalRef) -> FormData {
FormData {
reflector_: Reflector::new(),
data: DOMRefCell::new(HashMap::new()),
global: GlobalField::from_rooted(&global),
form: form.map(|f| JS::from_ref(f)),
}
}
pub fn new(form: ... | new_inherited | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding;
use dom::bindings::cod... | pub struct FormData {
reflector_: Reflector,
data: DOMRefCell<HashMap<DOMString, Vec<FormDatum>>>,
global: GlobalField,
form: Option<JS<HTMLFormElement>>
}
impl FormData {
fn new_inherited(form: Option<&HTMLFormElement>, global: GlobalRef) -> FormData {
FormData {
reflector_: Re... | random_line_split | |
astconv-cycle-between-trait-and-type.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 ... | fn dumber(&self, _: A) { }
}
struct SomeType<A>
where A : Trait1
{
a: A
}
impl Trait1 for u32 { }
impl Trait2<SomeType<u32>> for u32 { }
fn main() { } |
trait Trait2<A> { | random_line_split |
astconv-cycle-between-trait-and-type.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 ... | (&self, _: A) { }
}
struct SomeType<A>
where A : Trait1
{
a: A
}
impl Trait1 for u32 { }
impl Trait2<SomeType<u32>> for u32 { }
fn main() { }
| dumber | identifier_name |
astconv-cycle-between-trait-and-type.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 ... | { } | identifier_body | |
main.rs | extern crate piston_window;
extern crate yasss13rtwcf_shared as shared;
#[macro_use]
extern crate slog;
extern crate slog_term;
#[macro_use]
extern crate lazy_static;
extern crate gfx_device_gl;
extern crate image;
extern crate nalgebra;
extern crate input;
extern crate bytes;
extern crate tokio_io;
extern crate tokio_... |
let mut window: PistonWindow =
WindowSettings::new("YASSS13RTWCF", [640, 480]).exit_on_esc(true).build().unwrap();
make_builder(&WORLD)
.with_component(PositionComponent::empty())
.with_component(RenderableComponent::new(&Path::new("renderingtest.rsi"),
... | {
info!(LOGGER, "Starting client"; "version" => env!("CARGO_PKG_VERSION"));
{
// Register client components with the ECS world.
let mut world = WORLD.write().unwrap();
world.register_component::<RenderableComponent>();
}
// Asset dir is next to the executable, under "data".
... | identifier_body |
main.rs | extern crate piston_window;
extern crate yasss13rtwcf_shared as shared;
#[macro_use]
extern crate slog;
extern crate slog_term;
#[macro_use]
extern crate lazy_static;
extern crate gfx_device_gl;
extern crate image;
extern crate nalgebra;
extern crate input;
extern crate bytes;
extern crate tokio_io;
extern crate tokio_... |
});
}
}
| {
renderer.camera[(0, 0)] += 300.0 * delta;
} | conditional_block |
main.rs | extern crate piston_window;
extern crate yasss13rtwcf_shared as shared;
#[macro_use]
extern crate slog;
extern crate slog_term;
#[macro_use]
extern crate lazy_static;
extern crate gfx_device_gl;
extern crate image;
extern crate nalgebra;
extern crate input;
extern crate bytes;
extern crate tokio_io;
extern crate tokio_... | info!(LOGGER, "Loading asset directory"; "directory" => format!("{:?}", asset_dir));
load_from_dir(asset_dir).expect("Failed to load assets.");
let mut window: PistonWindow =
WindowSettings::new("YASSS13RTWCF", [640, 480]).exit_on_esc(true).build().unwrap();
make_builder(&WORLD)
.with_c... | asset_dir.push("data");
| random_line_split |
main.rs | extern crate piston_window;
extern crate yasss13rtwcf_shared as shared;
#[macro_use]
extern crate slog;
extern crate slog_term;
#[macro_use]
extern crate lazy_static;
extern crate gfx_device_gl;
extern crate image;
extern crate nalgebra;
extern crate input;
extern crate bytes;
extern crate tokio_io;
extern crate tokio_... | () {
info!(LOGGER, "Starting client"; "version" => env!("CARGO_PKG_VERSION"));
{
// Register client components with the ECS world.
let mut world = WORLD.write().unwrap();
world.register_component::<RenderableComponent>();
}
// Asset dir is next to the executable, under "data".
... | main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.