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
github.rs
//! Implements talking to the Github API use bytes::buf::BufExt as _; use futures::future::{BoxFuture, FutureExt, TryFutureExt}; use hyper; use hyper::{Body, Request, Response, StatusCode}; use mockall::automock; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json; use snafu::{ResultEx...
{ /// Failed to parse response as expected JSON object/ #[snafu(display("Failed to parse JSON response from GitHub: {}", source))] DeserializeError { source: serde_json::Error }, /// HTTP request failed/ #[snafu(display("Failed to send request to GitHub: {}", source))] Hyper { source: hyper::Er...
HttpError
identifier_name
github.rs
//! Implements talking to the Github API use bytes::buf::BufExt as _; use futures::future::{BoxFuture, FutureExt, TryFutureExt}; use hyper; use hyper::{Body, Request, Response, StatusCode}; use mockall::automock; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json; use snafu::{ResultEx...
/// Github API response to `/user/memberships/orgs/{org}` #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GithubOrganizationMembership { /// The user's membership state in the org state: String, /// The user's role in the org role: String, }
pub login: String, /// The user's Github display name (if any) pub name: Option<String>, }
random_line_split
consts.rs
#![allow(dead_code)] use winapi::*; //winsdk 7.0A windowx.h //pub const WM_CTLCOLOR: UINT = 0x0019; //winsdk 7.0A OleCtl.h pub const OCM__BASE: UINT = WM_USER + 0x1c00; pub const OCM_COMMAND: UINT = OCM__BASE + WM_COMMAND; pub const OCM_CTLCOLORBTN: UINT = OCM__BASE + WM_CTLCOLORBTN; pub const OCM_CTLCO...
pub const OCM_CHARTOITEM: UINT = OCM__BASE + WM_CHARTOITEM; pub const OCM_COMPAREITEM: UINT = OCM__BASE + WM_COMPAREITEM; pub const OCM_HSCROLL: UINT = OCM__BASE + WM_HSCROLL; pub const OCM_VSCROLL: UINT = OCM__BASE + WM_VSCROLL; pub const OCM_PARENTNOTIFY: UINT = OCM__BASE + WM_PARENTNOTIFY; pub const OCM_...
pub const OCM_VKEYTOITEM: UINT = OCM__BASE + WM_VKEYTOITEM;
random_line_split
borrowck-mut-borrow-of-mut-base-ptr.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 ...
{ }
identifier_body
borrowck-mut-borrow-of-mut-base-ptr.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 ...
} fn main() { }
random_line_split
borrowck-mut-borrow-of-mut-base-ptr.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 ...
<'a>(mut t0: &'a mut int, mut t1: &'a mut int) { let p: &mut int = &mut *t0; // Claims `*t0` let mut t2 = &mut t0; //~ ERROR cannot borrow `t0` **t2 += 1; // Mutates `*t0` but not through `*p` } fn main() { }
bar
identifier_name
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect(); assert!(v == Some(vec![])); let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect(); assert!(v == Some(vec![0, 1, 2])); let v: Option<Vec<int>> = range(0i, 3).map(|x| { if x > 1 { None } else { Some(x) } ...
test_collect
identifier_name
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_get_resource() { use std::rc::Rc; use core::cell::RefCell; struct R { i: Rc<RefCell<int>>, } #[unsafe_destructor] impl Drop for R { fn drop(&mut self) { let ii = &*self.i; let i = *ii.borrow(); *ii.borrow_mut() = i + 1; ...
assert_eq!(addr_x, addr_y); }
random_line_split
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_unwrap_or() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or(2), 1); let x: Option<int> = None; assert_eq!(x.unwrap_or(2), 2); } #[test] fn test_unwrap_or_else() { let x: Option<int> = Some(1); assert_eq!(x.unwrap_or_else(|| 2), 1); let x: Option<int> = None; a...
{ let x: Option<String> = None; x.unwrap(); }
identifier_body
deprecated.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
assert_eq!(find_deprecated(&{ let mut args = Args::default(); args.flag_jsonrpc = true; args.flag_rpc = true; args.flag_jsonrpc_off = true; args.flag_webapp = true; args.flag_dapps_off = true; args.flag_ipcdisable = true; args.flag_ipc_off = true; args.flag_etherbase = Some(Default::default...
random_line_split
deprecated.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
fn rpc() -> Self { Deprecated::DoesNothing("--rpc") } fn jsonrpc_off() -> Self { Deprecated::Replaced("--jsonrpc-off", "--no-jsonrpc") } fn webapp() -> Self { Deprecated::DoesNothing("--webapp") } fn dapps_off() -> Self { Deprecated::Replaced("--dapps-off", "--no-dapps") } fn ipcdisable() -> Self...
{ Deprecated::DoesNothing("--jsonrpc") }
identifier_body
deprecated.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
if args.flag_extradata.is_some() { result.push(Deprecated::extradata()); } result } #[cfg(test)] mod tests { use cli::Args; use super::{Deprecated, find_deprecated}; #[test] fn test_find_deprecated() { assert_eq!(find_deprecated(&Args::default()), vec![]); assert_eq!(find_deprecated(&{ let mut args...
{ result.push(Deprecated::etherbase()); }
conditional_block
deprecated.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
() -> Self { Deprecated::Replaced("--etherbase", "--author") } fn extradata() -> Self { Deprecated::Replaced("--extradata", "--extra-data") } } pub fn find_deprecated(args: &Args) -> Vec<Deprecated> { let mut result = vec![]; if args.flag_jsonrpc { result.push(Deprecated::jsonrpc()); } if args.flag_rpc...
etherbase
identifier_name
as_unsigned.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::slice::IntSliceExt; // pub trait IntSliceExt<U, S> { // /// Converts the slice to an immutable slice of unsigned integers with the same width. // fn as_unsigned<'a>(&'a self) -> &'a [U]; // /// Converts the slice t...
}
{ let slice: &[T] = &[0xff]; let as_unsigned: &[U] = slice.as_unsigned(); assert_eq!(as_unsigned[0], 255); }
identifier_body
as_unsigned.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::slice::IntSliceExt; // pub trait IntSliceExt<U, S> { // /// Converts the slice to an immutable slice of unsigned integers with the same width. // fn as_unsigned<'a>(&'a self) -> &'a [U]; // /// Converts the slice t...
() { let slice: &[T] = &[0xff]; let as_unsigned: &[U] = slice.as_unsigned(); assert_eq!(as_unsigned[0], 255); } }
as_unsigned_test1
identifier_name
as_unsigned.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::slice::IntSliceExt; // pub trait IntSliceExt<U, S> { // /// Converts the slice to an immutable slice of unsigned integers with the same width. // fn as_unsigned<'a>(&'a self) -> &'a [U]; // /// Converts the slice t...
// } // } // impl_int_slices! { u8, i8 } type U = u8; type S = i8; type T = S; #[test] #[allow(overflowing_literals)] fn as_unsigned_test1() { let slice: &[T] = &[0xff]; let as_unsigned: &[U] = slice.as_unsigned(); assert_eq!(as_unsigned[0], 255); } }
// macro_rules! impl_int_slices { // ($u:ty, $s:ty) => { // impl_int_slice! { $u, $s, $u } // impl_int_slice! { $u, $s, $s }
random_line_split
cargo.rs
extern crate cargo; extern crate env_logger; extern crate git2_curl; extern crate rustc_serialize; extern crate toml; #[macro_use] extern crate log; use std::collections::BTreeSet; use std::env; use std::fs; use std::io; use std::path::{PathBuf, Path}; use std::process::Command; use std::thread::Builder; use cargo::{...
_ => return } let handle = match cargo::ops::http_handle(config) { Ok(handle) => handle, Err(..) => return, }; // The unsafety of the registration function derives from two aspects: // // 1. This call must be synchronized with all other registration calls as // ...
{}
conditional_block
cargo.rs
extern crate cargo; extern crate env_logger; extern crate git2_curl; extern crate rustc_serialize; extern crate toml; #[macro_use] extern crate log; use std::collections::BTreeSet; use std::env; use std::fs; use std::io; use std::path::{PathBuf, Path}; use std::process::Command; use std::thread::Builder; use cargo::{...
for entry in entries { let entry = match entry { Ok(e) => e, Err(..) => continue }; let entry = entry.path(); let filename = match entry.file_name().and_then(|s| s.to_str()) { Some(filename) => filename, _ => continue }; ...
_ => continue };
random_line_split
cargo.rs
extern crate cargo; extern crate env_logger; extern crate git2_curl; extern crate rustc_serialize; extern crate toml; #[macro_use] extern crate log; use std::collections::BTreeSet; use std::env; use std::fs; use std::io; use std::path::{PathBuf, Path}; use std::process::Command; use std::thread::Builder; use cargo::{...
(path: &Path) -> bool { use std::os::unix::prelude::*; fs::metadata(path).map(|m| { m.permissions().mode() & 0o001 == 0o001 }).unwrap_or(false) } #[cfg(windows)] fn is_executable(path: &Path) -> bool { fs::metadata(path).map(|m| m.is_file()).unwrap_or(false) } /// Get `Command` to run given com...
is_executable
identifier_name
cargo.rs
extern crate cargo; extern crate env_logger; extern crate git2_curl; extern crate rustc_serialize; extern crate toml; #[macro_use] extern crate log; use std::collections::BTreeSet; use std::env; use std::fs; use std::io; use std::path::{PathBuf, Path}; use std::process::Command; use std::thread::Builder; use cargo::{...
/// List candidate locations where subcommands might be installed. fn list_command_directory() -> Vec<PathBuf> { let mut dirs = vec![]; if let Ok(mut path) = env::current_exe() { path.pop(); dirs.push(path.join("../lib/cargo")); dirs.push(path); } if let Some(val) = env::var_os...
{ let command_exe = format!("cargo-{}{}", cmd, env::consts::EXE_SUFFIX); let dirs = list_command_directory(); let mut command_paths = dirs.iter().map(|dir| dir.join(&command_exe)); command_paths.find(|path| fs::metadata(&path).is_ok()) }
identifier_body
challenge45.rs
use crate::errors::*; use dsa::{gen_range, Dsa, DsaParams, Signature}; use bignum::OpensslBigNum as BigNum; use bignum::{BigNumExt, BigNumTrait}; #[allow(clippy::many_single_char_names)] pub fn fake_signature(params: &DsaParams<BigNum>, y: &BigNum) -> Signature<BigNum> { let p = &params.p; let q = &params.q;...
() -> Result<()> { // It is not possible to fake a signature for g = 0 with our verification routine because r // would have to be 0. We therefore skip this part of the exercise. let params = DsaParams::new_with_g(BigNum::one()); let dsa = Dsa::generate_with_params(params); let signature = fake_sig...
run
identifier_name
challenge45.rs
use crate::errors::*;
use bignum::OpensslBigNum as BigNum; use bignum::{BigNumExt, BigNumTrait}; #[allow(clippy::many_single_char_names)] pub fn fake_signature(params: &DsaParams<BigNum>, y: &BigNum) -> Signature<BigNum> { let p = &params.p; let q = &params.q; let z = gen_range(&BigNum::from_u32(2), q); let r = y.mod_exp(&...
use dsa::{gen_range, Dsa, DsaParams, Signature};
random_line_split
challenge45.rs
use crate::errors::*; use dsa::{gen_range, Dsa, DsaParams, Signature}; use bignum::OpensslBigNum as BigNum; use bignum::{BigNumExt, BigNumTrait}; #[allow(clippy::many_single_char_names)] pub fn fake_signature(params: &DsaParams<BigNum>, y: &BigNum) -> Signature<BigNum>
pub fn run() -> Result<()> { // It is not possible to fake a signature for g = 0 with our verification routine because r // would have to be 0. We therefore skip this part of the exercise. let params = DsaParams::new_with_g(BigNum::one()); let dsa = Dsa::generate_with_params(params); let signatur...
{ let p = &params.p; let q = &params.q; let z = gen_range(&BigNum::from_u32(2), q); let r = y.mod_exp(&z, p).remainder(q); let s = (&r * &z.invmod(q).unwrap()).remainder(q); Signature { r, s } }
identifier_body
bernoulli.rs
use distribution; use random; /// A Bernoulli distribution. #[derive(Clone, Copy)] pub struct Bernoulli { p: f64, q: f64, pq: f64, } impl Bernoulli { /// Create a Bernoulli distribution with success probability `p`. /// /// It should hold that `p > 0` and `p < 1`. #[inline] pub fn new(...
() { assert_eq!(new!(0.25).variance(), 0.1875); } }
variance
identifier_name
bernoulli.rs
use distribution; use random; /// A Bernoulli distribution. #[derive(Clone, Copy)] pub struct Bernoulli { p: f64, q: f64, pq: f64, } impl Bernoulli { /// Create a Bernoulli distribution with success probability `p`. /// /// It should hold that `p > 0` and `p < 1`. #[inline] pub fn new(...
else { 1 } } } impl distribution::Kurtosis for Bernoulli { #[inline] fn kurtosis(&self) -> f64 { (1.0 - 6.0 * self.pq) / (self.pq) } } impl distribution::Mean for Bernoulli { #[inline] fn mean(&self) -> f64 { self.p } } impl distribution::Median for Bernoulli { fn median(&self) -...
{ 0 }
conditional_block
bernoulli.rs
use distribution; use random; /// A Bernoulli distribution. #[derive(Clone, Copy)] pub struct Bernoulli { p: f64, q: f64, pq: f64, } impl Bernoulli { /// Create a Bernoulli distribution with success probability `p`. /// /// It should hold that `p > 0` and `p < 1`. #[inline] pub fn new(...
#[test] fn median() { assert_eq!(new!(0.25).median(), 0.0); assert_eq!(new!(0.5).median(), 0.5); assert_eq!(new!(0.75).median(), 1.0); } #[test] fn modes() { assert_eq!(new!(0.25).modes(), vec![0]); assert_eq!(new!(0.5).modes(), vec![0, 1]); assert_eq...
assert_eq!(new!(0.5).mean(), 0.5); }
random_line_split
bernoulli.rs
use distribution; use random; /// A Bernoulli distribution. #[derive(Clone, Copy)] pub struct Bernoulli { p: f64, q: f64, pq: f64, } impl Bernoulli { /// Create a Bernoulli distribution with success probability `p`. /// /// It should hold that `p > 0` and `p < 1`. #[inline] pub fn new(...
/// Create a Bernoulli distribution with failure probability `q`. /// /// It should hold that `q > 0` and `q < 1`. This constructor is preferable /// when `q` is very small. #[inline] pub fn with_failure(q: f64) -> Bernoulli { should!(q > 0.0 && q < 1.0); Bernoulli { p: 1.0 - q...
{ should!(p > 0.0 && p < 1.0); Bernoulli { p: p, q: 1.0 - p, pq: p * (1.0 - p) } }
identifier_body
pipelinelatest_runartifacts.rs
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct Pipel...
}
{ PipelinelatestRunartifacts { name: None, size: None, url: None, _class: None, } }
identifier_body
pipelinelatest_runartifacts.rs
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct
{ #[serde(rename = "name", skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "size", skip_serializing_if = "Option::is_none")] pub size: Option<i32>, #[serde(rename = "url", skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(rename ...
PipelinelatestRunartifacts
identifier_name
pipelinelatest_runartifacts.rs
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct Pipel...
#[serde(rename = "_class", skip_serializing_if = "Option::is_none")] pub _class: Option<String>, } impl PipelinelatestRunartifacts { pub fn new() -> PipelinelatestRunartifacts { PipelinelatestRunartifacts { name: None, size: None, url: None, _class: N...
#[serde(rename = "url", skip_serializing_if = "Option::is_none")] pub url: Option<String>,
random_line_split
axum.rs
use axum::{ body::{boxed, Full}, handler::Handler, http::{header, StatusCode, Uri}, response::{Html, IntoResponse, Response}, routing::{get, Router}, }; use mime_guess; use rust_embed::RustEmbed; use std::net::SocketAddr; #[tokio::main] async fn main() { // Define our app routes, including a fallback optio...
() -> Html<&'static str> { Html("<h1>404</h1><p>Not Found</p>") } #[derive(RustEmbed)] #[folder = "examples/public/"] struct Asset; pub struct StaticFile<T>(pub T); impl<T> IntoResponse for StaticFile<T> where T: Into<String>, { fn into_response(self) -> Response { let path = self.0.into(); match Asse...
not_found
identifier_name
axum.rs
use axum::{ body::{boxed, Full}, handler::Handler, http::{header, StatusCode, Uri}, response::{Html, IntoResponse, Response}, routing::{get, Router}, }; use mime_guess; use rust_embed::RustEmbed; use std::net::SocketAddr; #[tokio::main] async fn main() {
.fallback(get(not_found)); // Start listening on the given address. let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("listening on {}", addr); axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap(); } // We use static route matchers ("/" and "/index.html") to serve our home //...
// Define our app routes, including a fallback option for anything not matched. let app = Router::new() .route("/", get(index_handler)) .route("/index.html", get(index_handler)) .route("/dist/*file", static_handler.into_service())
random_line_split
axum.rs
use axum::{ body::{boxed, Full}, handler::Handler, http::{header, StatusCode, Uri}, response::{Html, IntoResponse, Response}, routing::{get, Router}, }; use mime_guess; use rust_embed::RustEmbed; use std::net::SocketAddr; #[tokio::main] async fn main() { // Define our app routes, including a fallback optio...
StaticFile(path) } // Finally, we use a fallback route for anything that didn't match. async fn not_found() -> Html<&'static str> { Html("<h1>404</h1><p>Not Found</p>") } #[derive(RustEmbed)] #[folder = "examples/public/"] struct Asset; pub struct StaticFile<T>(pub T); impl<T> IntoResponse for StaticFile<T> w...
{ path = path.replace("dist/", ""); }
conditional_block
example_group.rs
use std::sync::{Arc, Mutex}; use std::fmt; use std::thread::JoinHandle; use std::panic::{recover, RecoverSafe, UnwindSafe}; use world_state; use util::{await_handles, SourceLocation}; use example::{Example, ExampleResult}; use example_group::example_group_result::{ExampleGroupResult}; use std::fmt::{Display, Formatter...
(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "`{}` at {}", self.description, self.source_location) } } pub struct ExampleGroup { examples: Vec<Example>, pub metadata: ExampleGroupMetadata } impl fmt::Debug for ExampleGroup { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt:...
fmt
identifier_name
example_group.rs
use std::sync::{Arc, Mutex}; use std::fmt; use std::thread::JoinHandle; use std::panic::{recover, RecoverSafe, UnwindSafe}; use world_state; use util::{await_handles, SourceLocation}; use example::{Example, ExampleResult}; use example_group::example_group_result::{ExampleGroupResult}; use std::fmt::{Display, Formatter...
} impl ExampleGroup { pub fn new(description: &str, source_location: SourceLocation) -> ExampleGroup { ExampleGroup { examples: Vec::new(), metadata: ExampleGroupMetadata { description: description.to_string(), source_location: source_location, ...
{ write!(formatter, "<Example group with metadata {:?}>", self.metadata) }
identifier_body
example_group.rs
use std::sync::{Arc, Mutex}; use std::fmt; use std::thread::JoinHandle; use std::panic::{recover, RecoverSafe, UnwindSafe}; use world_state; use util::{await_handles, SourceLocation}; use example::{Example, ExampleResult}; use example_group::example_group_result::{ExampleGroupResult}; use std::fmt::{Display, Formatter...
example.spawn(state) }).collect() } }
} fn build_running_examples(state: Arc<Mutex<world_state::WorldState>>, examples: Vec<Example>) -> Vec<JoinHandle<ExampleResult>> { examples.into_iter().map(|example| { let state = state.clone();
random_line_split
build.rs
use anyhow::{ensure, Context as _, Result}; use std::env; use std::fs; use std::path::{Path, PathBuf}; fn main() { let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let package_name = env::var("CARGO_PKG_NAME").unwrap(); let output_file = target_dir() .unwrap() .join(format!("{}-bindge...
() -> Result<PathBuf> { env::var("OUT_DIR") .map(PathBuf::from) .context("OUT_DIR is not set") } fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> { Ok(fs::canonicalize(path)?) } fn target_dir() -> Result<PathBuf> { let mut dir = out_dir().and_then(canonicalize)?; // println!("{...
out_dir
identifier_name
build.rs
use anyhow::{ensure, Context as _, Result};
fn main() { let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let package_name = env::var("CARGO_PKG_NAME").unwrap(); let output_file = target_dir() .unwrap() .join(format!("{}-bindgen", package_name)) .join(format!("{}.h", package_name)) .display() .to_string(); ...
use std::env; use std::fs; use std::path::{Path, PathBuf};
random_line_split
build.rs
use anyhow::{ensure, Context as _, Result}; use std::env; use std::fs; use std::path::{Path, PathBuf}; fn main() { let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let package_name = env::var("CARGO_PKG_NAME").unwrap(); let output_file = target_dir() .unwrap() .join(format!("{}-bindge...
ensure!(dir.pop(), "target dir is not found") } }
{ return Ok(dir); }
conditional_block
build.rs
use anyhow::{ensure, Context as _, Result}; use std::env; use std::fs; use std::path::{Path, PathBuf}; fn main() { let crate_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let package_name = env::var("CARGO_PKG_NAME").unwrap(); let output_file = target_dir() .unwrap() .join(format!("{}-bindge...
fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> { Ok(fs::canonicalize(path)?) } fn target_dir() -> Result<PathBuf> { let mut dir = out_dir().and_then(canonicalize)?; // println!("{:?}", dir); // eprintln!("{:?}", dir); loop { if dir.ends_with("target") { return Ok(d...
{ env::var("OUT_DIR") .map(PathBuf::from) .context("OUT_DIR is not set") }
identifier_body
walk-struct-literal-with.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn main(){ let start = Mine{test:"Foo".to_string(), other_val:0}; let end = Mine{other_val:1,..start.make_string_bar()}; println!("{}", start.test); //~ ERROR use of moved value: `start.test` }
{ self.test = "Bar".to_string(); self }
identifier_body
walk-struct-literal-with.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } fn main(){ let start = Mine{test:"Foo".to_string(), other_val:0}; let end = Mine{other_val:1,..start.make_string_bar()}; println!("{}", start.test); //~ ERROR use of moved value: `start.test` }
self
random_line_split
walk-struct-literal-with.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(mut self) -> Mine{ self.test = "Bar".to_string(); self } } fn main(){ let start = Mine{test:"Foo".to_string(), other_val:0}; let end = Mine{other_val:1,..start.make_string_bar()}; println!("{}", start.test); //~ ERROR use of moved value: `start.test` }
make_string_bar
identifier_name
loop-break-value.rs
// Copyright 2016 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 ...
} while let Some(_) = Some(()) { break None; //~^ ERROR `break` with value from a `while let` loop } 'while_let_loop: while let Some(_) = Some(()) { loop { break 'while_let_loop "nope"; //~^ ERROR `break` with value from a `while let` loop b...
{ //~ ERROR `break` with value from a `while let` loop }
conditional_block
loop-break-value.rs
// Copyright 2016 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 val:! = loop { break break; }; //~^ ERROR mismatched types loop { if true { break "asdf"; } else { break 123; //~ ERROR mismatched types } }; let _: i32 = loop { break "asdf"; //~ ERROR mismatched types }; let _: i32 = 'oute...
main
identifier_name
loop-break-value.rs
// Copyright 2016 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 ...
} while let Some(_) = Some(()) { break None; //~^ ERROR `break` with value from a `while let` loop } 'while_let_loop: while let Some(_) = Some(()) { loop { break 'while_let_loop "nope"; //~^ ERROR `break` with value from a `while let` loop br...
random_line_split
loop-break-value.rs
// Copyright 2016 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 ...
}; }; 'while_loop: while true { break; break (); //~ ERROR `break` with value from a `while` loop loop { break 'while_loop 123; //~^ ERROR `break` with value from a `while` loop break 456; break 789; }; } while let...
{ let val: ! = loop { break break; }; //~^ ERROR mismatched types loop { if true { break "asdf"; } else { break 123; //~ ERROR mismatched types } }; let _: i32 = loop { break "asdf"; //~ ERROR mismatched types }; let _: i32 = 'outer_...
identifier_body
main.rs
use std::env::args; fn fuel_required(mass: i32) -> i32 { (mass / 3) - 2 } fn full_fuel_required(mass: i32) -> i32
fn main() { let modules: Vec<i32> = args().skip(1).map(|arg| { arg.parse().unwrap() }).collect(); let total_fuel: i32 = modules.iter().map(|module| { fuel_required(*module) }).sum(); let full_total_fuel: i32 = modules.iter().map(|module| { full_fuel_required(*module) }).sum(); println!("...
{ let mut fuel = fuel_required(mass); let mut new_fuel = fuel_required(fuel); while new_fuel > 0 { fuel += new_fuel; new_fuel = fuel_required(new_fuel); } fuel }
identifier_body
main.rs
use std::env::args; fn fuel_required(mass: i32) -> i32 { (mass / 3) - 2 } fn
(mass: i32) -> i32 { let mut fuel = fuel_required(mass); let mut new_fuel = fuel_required(fuel); while new_fuel > 0 { fuel += new_fuel; new_fuel = fuel_required(new_fuel); } fuel } fn main() { let modules: Vec<i32> = args().skip(1).map(|arg| { arg.parse().unwrap() }...
full_fuel_required
identifier_name
main.rs
use std::env::args; fn fuel_required(mass: i32) -> i32 { (mass / 3) - 2 } fn full_fuel_required(mass: i32) -> i32 { let mut fuel = fuel_required(mass); let mut new_fuel = fuel_required(fuel);
fuel += new_fuel; new_fuel = fuel_required(new_fuel); } fuel } fn main() { let modules: Vec<i32> = args().skip(1).map(|arg| { arg.parse().unwrap() }).collect(); let total_fuel: i32 = modules.iter().map(|module| { fuel_required(*module) }).sum(); let full_total_fuel: i3...
while new_fuel > 0 {
random_line_split
url.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 extra::url; use extra::url::Url; use collections::HashMap; use std::os; /** Create a URL object from a string...
pub fn is_image_data(uri: &str) -> bool { static types: &'static [&'static str] = &[&"data:image/png", &"data:image/gif", &"data:image/jpeg"]; types.iter().any(|&type_| uri.starts_with(type_)) }
random_line_split
url.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 extra::url; use extra::url::Url; use collections::HashMap; use std::os; /** Create a URL object from a string...
#[test] fn should_create_url_based_on_old_url_3() { let old_str = "http://example.com/index.html"; let old_url = parse_url(old_str, None); let new_str = "crumpet.html"; let new_url = parse_url(new_str, Some(old_url)); assert!(new_url.scheme == ~"http"); assert!(...
{ let old_str = "http://example.com/"; let old_url = parse_url(old_str, None); let new_str = "index.html"; let new_url = parse_url(new_str, Some(old_url)); assert!(new_url.scheme == ~"http"); assert!(new_url.host == ~"example.com"); assert!(new_url.path == ~"/inde...
identifier_body
url.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 extra::url; use extra::url::Url; use collections::HashMap; use std::os; /** Create a URL object from a string...
() { let old_str = "http://example.com/index.html"; let old_url = parse_url(old_str, None); let new_str = "crumpet.html"; let new_url = parse_url(new_str, Some(old_url)); assert!(new_url.scheme == ~"http"); assert!(new_url.host == ~"example.com"); assert!(new_url....
should_create_url_based_on_old_url_3
identifier_name
url.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 extra::url; use extra::url::Url; use collections::HashMap; use std::os; /** Create a URL object from a string...
"failure" => { let mut path = os::self_exe_path().expect("can't get exe path"); path.push("../src/test/html/failure.html"); // FIXME (#1094): not the right way to transform a path ~"f...
{ fail!("about:crash"); }
conditional_block
mtime.rs
use std::fmt; use std::fs; use std::io; use std::path::Path; /// A helper structure to represent the modification time of a file. /// /// The actual value contained within is platform-specific and does not have the /// same meaning across platforms, but comparisons and stringification can be /// significant among plat...
#[cfg(windows)] fn from(meta: &'a fs::Metadata) -> MTime { use std::os::windows::prelude::*; // Windows write times are in 100ns intervals, so do a little math to // get it into the right representation. let time = meta.last_write_time(); MTime { seconds: t...
{ use std::os::unix::prelude::*; let raw = meta.as_raw(); // FIXME: currently there is a bug in the standard library where the // nanosecond accessor is just accessing the seconds again, once // that bug is fixed this should take nanoseconds into account. MT...
identifier_body
mtime.rs
use std::fmt; use std::fs; use std::io; use std::path::Path; /// A helper structure to represent the modification time of a file. /// /// The actual value contained within is platform-specific and does not have the /// same meaning across platforms, but comparisons and stringification can be /// significant among plat...
impl MTime { pub fn zero() -> MTime { MTime { seconds: 0, nanos: 0 } } pub fn of(p: &Path) -> io::Result<MTime> { let metadata = try!(fs::metadata(p)); Ok(MTime::from(&metadata)) } } impl<'a> From<&'a fs::Metadata> for MTime { #[cfg(unix)] fn from(meta: &'a fs::Metadat...
random_line_split
mtime.rs
use std::fmt; use std::fs; use std::io; use std::path::Path; /// A helper structure to represent the modification time of a file. /// /// The actual value contained within is platform-specific and does not have the /// same meaning across platforms, but comparisons and stringification can be /// significant among plat...
(p: &Path) -> io::Result<MTime> { let metadata = try!(fs::metadata(p)); Ok(MTime::from(&metadata)) } } impl<'a> From<&'a fs::Metadata> for MTime { #[cfg(unix)] fn from(meta: &'a fs::Metadata) -> MTime { use std::os::unix::prelude::*; let raw = meta.as_raw(); // FIXME...
of
identifier_name
mod.rs
//! # Utility module #[cfg(test)] pub mod test; use std::ops::Range; use std::slice::from_raw_parts; /// Constant used when unwrapping an empty `Option<u16>` pub const DEAD: u16 = 0xdead; /// Constant used when unwrapping an empty `Option<u32>` pub const DEADBEEF: u32 = 0xdeadbeef; /// A slice of bytes. /// /// It...
/// Returns a copy of the original slice, minus the `n` first elements. pub fn skip<'a>(original: &'a [u8], n: usize) -> &'a [u8] { if n == 0 { return original; } let mut iter = original.iter(); iter.nth(n.wrapping_sub(1)); // O(1) iter.as_slice() } /// Returns a copy of the original slice, minus an...
{ if range.start <= range.end && range.end <= original.len() { Some( take( skip(original, range.start), range.end.wrapping_sub(range.start) ) ) } else { None } }
identifier_body
mod.rs
//! # Utility module #[cfg(test)] pub mod test; use std::ops::Range; use std::slice::from_raw_parts; /// Constant used when unwrapping an empty `Option<u16>` pub const DEAD: u16 = 0xdead; /// Constant used when unwrapping an empty `Option<u32>` pub const DEADBEEF: u32 = 0xdeadbeef; /// A slice of bytes. /// /// It...
else { None } } /// Returns a u16 interpreting the first 2 bytes of the slice in little-endian /// encoding, or `None` if the slice is too short. /// /// Does not assume that the data is suitably aligned. pub fn read_u16_le<'a>(slice: Slice<'a>) -> Option<u16> { match (slice.get(0), slice.get(1)) { ...
{ Some(needle.wrapping_sub(hay)) }
conditional_block
mod.rs
//! # Utility module #[cfg(test)] pub mod test; use std::ops::Range; use std::slice::from_raw_parts; /// Constant used when unwrapping an empty `Option<u16>` pub const DEAD: u16 = 0xdead; /// Constant used when unwrapping an empty `Option<u32>` pub const DEADBEEF: u32 = 0xdeadbeef; /// A slice of bytes. /// /// It...
.unwrap_or(DEADBEEF) } /// Optional binary field of a given length at a given index. fn read_field(&self, index: usize, length: usize) -> Option<&'a [u8]> { self.get_slice().slice(index..(index + length)).map(|s| s.raw()) } } /// Returns the elements of the `hay` slice that overlap ...
self.get_slice() .slice(range) .and_then(read_u32_le)
random_line_split
mod.rs
//! # Utility module #[cfg(test)] pub mod test; use std::ops::Range; use std::slice::from_raw_parts; /// Constant used when unwrapping an empty `Option<u16>` pub const DEAD: u16 = 0xdead; /// Constant used when unwrapping an empty `Option<u32>` pub const DEADBEEF: u32 = 0xdeadbeef; /// A slice of bytes. /// /// It...
<'a>(original: &'a [u8], n: usize) -> &'a [u8] { use std::cmp::min; // TODO: replace with safe code // // While the following code optimizes well: // ``` // let take_back = original.len().wrapping_sub(n).wrapping_sub(1); // let mut iter = original.iter(); // iter.rev().nth(take_back); /...
take
identifier_name
core.rs
use std::ffi::OsString; use std::fs; use std::fs::Permissions; use std::io; use std::io::Stderr; use std::io::Stdin; use std::io::Stdout; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use structopt::StructOpt; use super::Error; use super::Result; enum Context { /// The path is ...
return Ok(()); } } if!self.options.dry_run { // Change the mode of the path fs::set_permissions(path, Permissions::from_mode(mode))?; if self.options.verbose { // Write the results (optional) self.write_res...
fn change_one_inner(&mut self, path: &PathBuf, mode: u32) -> Result<()> { if self.options.interactive && !self.options.suppress { // Authorize every path (optional) if let Ok(false) = self.auth(path, Context::Interactive) {
random_line_split
core.rs
use std::ffi::OsString; use std::fs; use std::fs::Permissions; use std::io; use std::io::Stderr; use std::io::Stdin; use std::io::Stdout; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use structopt::StructOpt; use super::Error; use super::Result; enum Context { /// The path is ...
(&mut self, msg: &str, path: &PathBuf) -> Result<()> { writeln!(self.stdout, r#""{}": mode {}."#, path.display(), msg)?; return Ok(()); } }
write_result
identifier_name
core.rs
use std::ffi::OsString; use std::fs; use std::fs::Permissions; use std::io; use std::io::Stderr; use std::io::Stdin; use std::io::Stdout; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use structopt::StructOpt; use super::Error; use super::Result; enum Context { /// The path is ...
/// Replaces the standard input stream for this program. pub fn stdin(&mut self, stdin: Stdin) -> &mut Self { self.stdin = stdin; return self; } /// Runs this program and writes all errors. pub fn run(&mut self) -> Result<()> { match self.run_inner() { Ok(val) ...
{ self.stdout = stdout; return self; }
identifier_body
errorevent.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::ErrorEvent...
(global: GlobalRef, type_: DOMString, bubbles: EventBubbles, cancelable: EventCancelable, message: DOMString, filename: DOMString, lineno: u32, colno: u32, error: JSVal) -> Temporary<ErrorEvent> { ...
new
identifier_name
errorevent.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::ErrorEvent...
Some(filename) => filename.clone(), }; let line_num = init.lineno.unwrap_or(0); let col_num = init.colno.unwrap_or(0); let bubbles = if init.parent.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; let cancelable = if init.parent.cancelable {...
let file_name = match init.filename.as_ref() { None => "".to_owned(),
random_line_split
errorevent.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::ErrorEvent...
fn Message(self) -> DOMString { // FIXME(https://github.com/rust-lang/rust/issues/23338) let message = self.message.borrow(); message.clone() } fn Filename(self) -> DOMString { // FIXME(https://github.com/rust-lang/rust/issues/23338) let filename = self.filename.bo...
{ self.colno.get() }
identifier_body
errorevent.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::ErrorEvent...
; let cancelable = if init.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let event = ErrorEvent::new(global, type_, bubbles, cancelable, msg, file_name, ...
{ EventBubbles::DoesNotBubble }
conditional_block
lib.rs
/* Copyright ⓒ 2015 Daniel Keep. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distribu...
#[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.count, Some(self.count)) } }
match self.item.take() { Some(v) => { self.count -= 1; Some(v) }, None => None } }
identifier_body
lib.rs
/* Copyright ⓒ 2015 Daniel Keep. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distribu...
mut self) -> Option<T> { match self.item.take() { Some(v) => { self.count -= 1; Some(v) }, None => None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.count, Some(self.count)) } }
xt(&
identifier_name
lib.rs
/* Copyright ⓒ 2015 Daniel Keep. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modified, or distribu...
This is necessary because of how `Extend` is implemented for `Vec`: specifically, it asks for the first element *before* it checks `size_hint`. As a result, the old trick (of having an empty iterator that reported a false size hint) doesn't work. */ #[doc(hidden)] pub struct SizeHintIter<T> { pub item: Option<T>, ...
/** This iterator's whole purpose in life is to lie whenever it's asked how many items it has.
random_line_split
main.rs
use std::fmt; #[derive(Debug)] struct A1(i64, i64); impl fmt::Display for A1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } #[derive(Debug)] struct A2D { x: f64, y: f64, } impl fmt::Display for A2D { fn fmt(&self, f: &mut fmt::Formatter...
let lon_c = if self.lon >= 0.0 { "东经" } else { "西经" }; write!(f, "{}: {}{:.3}° {}{:.3}°", self.name, lat_c, self.lat.abs(), lon_c, self.lon.abs()) } } struct Color { r: u8, g: u8, b: u8, } impl fmt::Display for Color { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result ...
纬" };
conditional_block
main.rs
use std::fmt; #[derive(Debug)] struct A1(i64, i64); impl fmt::Display for A1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } #[derive(Debug)] struct A2D { x: f64, y: f64, } impl fmt::Display for A2D { fn fmt(&self, f: &mut fmt::Formatter...
} struct List(Vec<i32>); impl fmt::Display for List { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let List(ref vec) = *self; try!(write!(f, "[")); for (count, v) in vec.iter().enumerate() { if count!= 0 { try!(write!(f, ", ")); } ...
{ write!(f, "{} + {}i", self.real, self.imag) }
identifier_body
main.rs
use std::fmt; #[derive(Debug)] struct A1(i64, i64); impl fmt::Display for A1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } #[derive(Debug)] struct A2D { x: f64, y: f64, } impl fmt::Display for A2D { fn fmt(&self, f: &mut fmt::Formatter...
println!("{}", d); for city in [ City { name: "北京", lat: 39.67, lon: 116.40}, City { name: "上海", lat: 31.23, lon: 121.47}, City { name: "广州", lat: 23.13, lon: 113.26}, City { name: "深圳", lat: 22.54, lon: 114.05}, City { name: "杭州", lat: 30.27, lon: 120.15}, City...
random_line_split
main.rs
use std::fmt; #[derive(Debug)] struct A1(i64, i64); impl fmt::Display for A1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } #[derive(Debug)] struct A2D { x: f64, y: f64, } impl fmt::Display for A2D { fn fmt(&self, f: &mut fmt::Formatter...
(&self, f: &mut fmt::Formatter) -> fmt::Result { let List(ref vec) = *self; try!(write!(f, "[")); for (count, v) in vec.iter().enumerate() { if count!= 0 { try!(write!(f, ", ")); } try!(write!(f, "{}: {}", count, v)); } write...
fmt
identifier_name
main.rs
#![feature(plugin)] #![plugin(clippy)] extern crate calamine; extern crate hyper; use std::fs; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use std::str; use hyper::client::Client; mod excel; fn main() { fs::create_dir_all("data").unwrap(); let csv = Path::new("data/foo.csv"); le...
(url: &str, xls: &Path) { let mut response = Client::new().get(url).send().unwrap(); let mut buf = Vec::new(); response.read_to_end(&mut buf).unwrap(); let mut file = File::create(&xls).unwrap(); file.write_all(&buf).unwrap(); }
download
identifier_name
main.rs
#![feature(plugin)] #![plugin(clippy)] extern crate calamine; extern crate hyper; use std::fs; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use std::str; use hyper::client::Client; mod excel; fn main()
fn download(url: &str, xls: &Path) { let mut response = Client::new().get(url).send().unwrap(); let mut buf = Vec::new(); response.read_to_end(&mut buf).unwrap(); let mut file = File::create(&xls).unwrap(); file.write_all(&buf).unwrap(); }
{ fs::create_dir_all("data").unwrap(); let csv = Path::new("data/foo.csv"); let url = "https://www.spdrs.com/site-content/xls/SPY_All_Holdings.\ xls?fund=SPY&docname=All+Holdings&onyx_code1=1286&onyx_code2=1700"; let worksheet = "SPY_All_Holdings"; let xls = Path::new("data/foo.xls"); ...
identifier_body
main.rs
#![feature(plugin)] #![plugin(clippy)] extern crate calamine; extern crate hyper; use std::fs; use std::fs::File; use std::io::{Read, Write}; use std::path::Path; use std::str; use hyper::client::Client;
let url = "https://www.spdrs.com/site-content/xls/SPY_All_Holdings.\ xls?fund=SPY&docname=All+Holdings&onyx_code1=1286&onyx_code2=1700"; let worksheet = "SPY_All_Holdings"; let xls = Path::new("data/foo.xls"); download(url, xls); excel::excel_to_csv(csv, xls, worksheet); } fn download(url...
mod excel; fn main() { fs::create_dir_all("data").unwrap(); let csv = Path::new("data/foo.csv");
random_line_split
reftest.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
use extra::test::run_tests_console; fn main() { let args = os::args(); if args.len() < 2 { println("error: at least one reftest list must be given"); os::set_exit_status(1); return; } let tests = parse_lists(args.tail()); let test_opts = TestOpts { filter: None, ...
use extra::test::{DynTestName, DynTestFn, TestDesc, TestOpts, TestDescAndFn};
random_line_split
reftest.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
{ Same, Different, } struct Reftest { name: ~str, kind: ReftestKind, left: ~str, right: ~str, id: uint, } fn parse_lists(filenames: &[~str]) -> ~[TestDescAndFn] { let mut tests: ~[TestDescAndFn] = ~[]; let mut next_id = 0; for file in filenames.iter() { let file_path =...
ReftestKind
identifier_name
reftest.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 ...
"#" => continue, _ => fail!("reftest line: '{:s}' has invalid kind '{:s}'", line, parts[0]) }; let src_path = file_path.dir_path(); let src_dir = src_path.display().to_str(); let file_left = src_dir + "/" + parts...
{ let mut tests: ~[TestDescAndFn] = ~[]; let mut next_id = 0; for file in filenames.iter() { let file_path = Path::new(file.clone()); let contents = match File::open_mode(&file_path, io::Open, io::Read) { Some(mut f) => str::from_utf8_owned(f.read_to_end()), None => f...
identifier_body
stylesheet_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 document_loader::LoadType; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; u...
} } } pub struct StylesheetLoader<'a> { elem: &'a HTMLElement, } impl<'a> StylesheetLoader<'a> { pub fn for_element(element: &'a HTMLElement) -> Self { StylesheetLoader { elem: element, } } } impl<'a> StylesheetLoader<'a> { pub fn load(&self, source: Stylesheet...
if let Some(any_failed) = owner.load_finished(successful) { let event = if any_failed { atom!("error") } else { atom!("load") }; elem.upcast::<EventTarget>().fire_event(event);
random_line_split
stylesheet_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 document_loader::LoadType; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; u...
(&self, import: &Arc<RwLock<ImportRule>>) { self.load(StylesheetContextSource::Import(import.clone()), "".to_owned()) } }
request_stylesheet
identifier_name
stylesheet_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 document_loader::LoadType; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; u...
fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.metadata = metadata.ok().map(|m| { match m { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsafe_,.. } => unsafe_ } }...
{}
identifier_body
mod.rs
// // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or othe...
// Copyright (c) 2016-2018 Bruce Stenning. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met:
random_line_split
invite_resolvers.rs
use chrono::prelude::*; use async_graphql::{ FieldResult, ID, }; // use eyre::{ // // eyre, // Result, // // Context as _, // }; use printspool_config_form::ConfigForm; use crate::invite::Invite; #[async_graphql::Object] impl Invite { async fn id(&self) -> ID { (&self.id).into() } ...
}
{ let config_form = printspool_config_form::into_config_form(self)?; Ok(config_form) }
identifier_body
invite_resolvers.rs
use chrono::prelude::*; use async_graphql::{ FieldResult, ID, }; // use eyre::{ // // eyre, // Result, // // Context as _, // }; use printspool_config_form::ConfigForm; use crate::invite::Invite; #[async_graphql::Object] impl Invite { async fn id(&self) -> ID { (&self.id).into() } ...
(&self) -> String { self.config.name .clone() .and_then(|s| if s.is_empty() { None } else { Some(s) } ) .unwrap_or_else(|| format!("Invite #{}", self.id).to_string()) } a...
description
identifier_name
invite_resolvers.rs
use chrono::prelude::*; use async_graphql::{ FieldResult, ID, }; // use eyre::{ // // eyre, // Result, // // Context as _, // }; use printspool_config_form::ConfigForm; use crate::invite::Invite; #[async_graphql::Object] impl Invite { async fn id(&self) -> ID { (&self.id).into() } ...
} else { Some(s) } ) .unwrap_or_else(|| format!("Invite #{}", self.id).to_string()) } async fn is_admin(&self) -> bool { self.config.is_admin } async fn created_at(&self) -> DateTime<Utc> { self.created_at } ...
None
random_line_split
invite_resolvers.rs
use chrono::prelude::*; use async_graphql::{ FieldResult, ID, }; // use eyre::{ // // eyre, // Result, // // Context as _, // }; use printspool_config_form::ConfigForm; use crate::invite::Invite; #[async_graphql::Object] impl Invite { async fn id(&self) -> ID { (&self.id).into() } ...
) .unwrap_or_else(|| format!("Invite #{}", self.id).to_string()) } async fn is_admin(&self) -> bool { self.config.is_admin } async fn created_at(&self) -> DateTime<Utc> { self.created_at } async fn config_form(&self) -> FieldResult<ConfigForm> { ...
{ Some(s) }
conditional_block
etl.rs
extern crate etl; use std::collections::BTreeMap; #[test] fn test_transform_one_value() { let input = input_from(&[ (1, vec!("WORLD")), ]); let expected = expected_from(&[ ("world", 1), ]); assert_eq!(expected, etl::transform(&input)); } #[test] #[ignore] fn test_transform_more_...
() { let input = input_from(&[ (1, vec!("A", "E", "I", "O", "U", "L", "N", "R", "S", "T")), (2, vec!("D", "G")), (3, vec!("B", "C", "M", "P")), (4, vec!("F", "H", "V", "W", "Y")), (5, vec!("K")), (8, vec!("J", "X")), (10, vec!("Q", "Z")), ]); le...
test_full_dataset
identifier_name
etl.rs
extern crate etl; use std::collections::BTreeMap; #[test] fn test_transform_one_value() { let input = input_from(&[ (1, vec!("WORLD")), ]);
assert_eq!(expected, etl::transform(&input)); } #[test] #[ignore] fn test_transform_more_values() { let input = input_from(&[ (1, vec!("WORLD", "GSCHOOLERS")), ]); let expected = expected_from(&[ ("world", 1), ("gschoolers", 1), ]); assert_eq!(expected, etl::transform(&input))...
let expected = expected_from(&[ ("world", 1), ]);
random_line_split
etl.rs
extern crate etl; use std::collections::BTreeMap; #[test] fn test_transform_one_value()
#[test] #[ignore] fn test_transform_more_values() { let input = input_from(&[ (1, vec!("WORLD", "GSCHOOLERS")), ]); let expected = expected_from(&[ ("world", 1), ("gschoolers", 1), ]); assert_eq!(expected, etl::transform(&input)); } #[test] #[ignore] fn test_more_keys() { le...
{ let input = input_from(&[ (1, vec!("WORLD")), ]); let expected = expected_from(&[ ("world", 1), ]); assert_eq!(expected, etl::transform(&input)); }
identifier_body
client.rs
#![deny(warnings)] #![feature(test)] extern crate hyper; extern crate test; use std::fmt; use std::io::{self, Read, Write, Cursor}; use std::net::SocketAddr; use std::time::Duration; use hyper::net; static README: &'static [u8] = include_bytes!("../README.md"); struct MockStream { read: Cursor<Vec<u8>> } impl...
(b: &mut test::Bencher) { let url = "http://127.0.0.1:1337/"; b.iter(|| { let mut req = hyper::client::Request::with_connector( hyper::Get, hyper::Url::parse(url).unwrap(), &MockConnector ).unwrap(); req.headers_mut().set(Foo); let mut s = String::new(); req ...
bench_mock_hyper
identifier_name
client.rs
#![deny(warnings)] #![feature(test)] extern crate hyper; extern crate test; use std::fmt; use std::io::{self, Read, Write, Cursor}; use std::net::SocketAddr; use std::time::Duration; use hyper::net; static README: &'static [u8] = include_bytes!("../README.md"); struct MockStream { read: Cursor<Vec<u8>> } impl...
fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[derive(Clone, Debug)] struct Foo; impl hyper::header::Header for Foo { fn header_name() -> &'static str { "x-foo" } fn parse_header(_: &[Vec<u8>]) -> hyper::Result<Foo> { Err(hyper::Error::Header) } } impl hyper::he...
{ // we're mocking, what do we care. Ok(msg.len()) }
identifier_body
client.rs
#![deny(warnings)] #![feature(test)] extern crate hyper; extern crate test; use std::fmt; use std::io::{self, Read, Write, Cursor}; use std::net::SocketAddr; use std::time::Duration; use hyper::net; static README: &'static [u8] = include_bytes!("../README.md"); struct MockStream { read: Cursor<Vec<u8>> } impl...
read: Cursor::new(self.read.get_ref().clone()) } } } impl Read for MockStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.read.read(buf) } } impl Write for MockStream { fn write(&mut self, msg: &[u8]) -> io::Result<usize> { // we're mocking, wha...
impl Clone for MockStream { fn clone(&self) -> MockStream { MockStream {
random_line_split
int_macros.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...
) }
random_line_split
simplify_newtypes.rs
use analysis::Loc; use ir::{Function, Instruction, Program, Reg, Value}; use optimization::{self as opt, Rewriter}; use std::collections::HashMap; #[derive(Default)] struct Simplifier { reg_size: HashMap<Reg, u32>, } impl Simplifier { fn value_size(&self, val: &Value) -> u32 { match *val { ...
} if let Some(new) = result { *instr = new; } } } pub fn rewrite(program: &mut Program) { Simplifier::default().rewrite_program(program); }
if self.reg_size[&reg] == self.reg_size[&reg2] { result = Some(Instruction::Assign(reg, Value::Reg(reg2))) } } _ => {}
random_line_split
simplify_newtypes.rs
use analysis::Loc; use ir::{Function, Instruction, Program, Reg, Value}; use optimization::{self as opt, Rewriter}; use std::collections::HashMap; #[derive(Default)] struct Simplifier { reg_size: HashMap<Reg, u32>, } impl Simplifier { fn value_size(&self, val: &Value) -> u32
} impl Rewriter for Simplifier { fn rewrite_function(&mut self, f: &mut Function) { self.reg_size = f .registers .iter() .map(|(&reg, &layout)| (reg, layout.size)) .collect(); opt::rewrite_function(self, f); } fn rewrite_instruction(&mut self, _...
{ match *val { Value::Undef => 1, Value::Bytes(_) => ::ir::POINTER_SIZE, Value::Int(_, size) => size.in_bytes(), Value::Reg(reg) => self.reg_size[&reg], Value::Symbol(_) => ::ir::FUNCTION_SIZE, } }
identifier_body
simplify_newtypes.rs
use analysis::Loc; use ir::{Function, Instruction, Program, Reg, Value}; use optimization::{self as opt, Rewriter}; use std::collections::HashMap; #[derive(Default)] struct Simplifier { reg_size: HashMap<Reg, u32>, } impl Simplifier { fn value_size(&self, val: &Value) -> u32 { match *val { ...
(program: &mut Program) { Simplifier::default().rewrite_program(program); }
rewrite
identifier_name
ac97_mixer.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::pci::ac97_regs::*; // AC97 Vendor ID const AC97_VENDOR_ID1: u16 = 0x8086; const AC97_VENDOR_ID2: u16 = 0x8086; // Extented Audio ID const A...
fn set_record_gain_reg(&mut self, val: u16) { self.record_gain_mute = val & MUTE_REG_BIT!= 0; self.record_gain_r = (val & VOL_REG_MASK) as u8; self.record_gain_l = (val >> 8 & VOL_REG_MASK) as u8; } // Handles writes to the powerdown ctrl/status register (0x26). fn set_power_dow...
// Handles writes to the record_gain register (0x1c).
random_line_split