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 |
|---|---|---|---|---|
random_seed.rs | use chapter2::dungeon::{Dungeon};
use chapter2::genotype::{Genotype};
use chapter2::phenotype::{Seed};
use rand::{Rng, thread_rng};
#[derive(Clone, Debug)]
pub struct RandomSeed {
seed: Seed,
}
impl RandomSeed { | RandomSeed {
seed: seed.clone(),
}
}
}
impl Genotype for RandomSeed {
fn generate(&self) -> Dungeon {
let mut rng = thread_rng();
let w = self.seed.width;
let h = self.seed.height;
let mut dungeon = Dungeon::new(w, h, None);
for i in 0..dungeo... | pub fn new(seed: &Seed) -> RandomSeed { | random_line_split |
random_seed.rs | use chapter2::dungeon::{Dungeon};
use chapter2::genotype::{Genotype};
use chapter2::phenotype::{Seed};
use rand::{Rng, thread_rng};
#[derive(Clone, Debug)]
pub struct RandomSeed {
seed: Seed,
}
impl RandomSeed {
pub fn new(seed: &Seed) -> RandomSeed {
RandomSeed {
seed: seed.clone(),
... | (&self) -> Dungeon {
let mut rng = thread_rng();
let w = self.seed.width;
let h = self.seed.height;
let mut dungeon = Dungeon::new(w, h, None);
for i in 0..dungeon.width as u32 {
for j in 0..dungeon.height as u32 {
let tile = self.seed.tiles.choose(&mu... | generate | identifier_name |
generic-static-methods.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 ... | } | random_line_split | |
generic-static-methods.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 ... |
}
pub fn main() {
assert_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
}
| {
let mut r = Vec::new();
for elt in x.iter() {
r.push(f(elt));
}
r
} | identifier_body |
generic-static-methods.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 ... | <U>(x: &Vec<T>, f: |&T| -> U) -> Vec<U> {
let mut r = Vec::new();
for elt in x.iter() {
r.push(f(elt));
}
r
}
}
pub fn main() {
assert_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
}
| map_ | identifier_name |
sodium.rs | extern crate sodiumoxide;
use errors::prelude::*;
use failure::{err_msg, ResultExt};
use self::sodiumoxide::crypto::secretbox;
use self::sodiumoxide::crypto::secretbox::xsalsa20poly1305;
pub const KEYBYTES: usize = xsalsa20poly1305::KEYBYTES;
pub const NONCEBYTES: usize = xsalsa20poly1305::NONCEBYTES;
pub const MACBY... | (key: &Key, nonce: &Nonce, doc: &[u8]) -> (Vec<u8>, Tag) {
let mut cipher = doc.to_vec();
let tag = secretbox::seal_detached(cipher.as_mut_slice(),
&nonce.0,
&key.0);
(cipher, Tag(tag))
}
pub fn decrypt_detached(key: &Key, nonce: &Nonce, tag... | encrypt_detached | identifier_name |
sodium.rs | extern crate sodiumoxide;
use errors::prelude::*;
use failure::{err_msg, ResultExt};
use self::sodiumoxide::crypto::secretbox;
use self::sodiumoxide::crypto::secretbox::xsalsa20poly1305;
pub const KEYBYTES: usize = xsalsa20poly1305::KEYBYTES;
pub const NONCEBYTES: usize = xsalsa20poly1305::NONCEBYTES;
pub const MACBY... |
pub fn gen_nonce() -> Nonce {
Nonce(secretbox::gen_nonce())
}
pub fn encrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Vec<u8> {
secretbox::seal(
doc,
&nonce.0,
&key.0,
)
}
pub fn decrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Result<Vec<u8>, IndyError> {
secretbox::open(
... | {
Key(secretbox::gen_key())
} | identifier_body |
sodium.rs | extern crate sodiumoxide;
use errors::prelude::*;
use failure::{err_msg, ResultExt};
use self::sodiumoxide::crypto::secretbox;
use self::sodiumoxide::crypto::secretbox::xsalsa20poly1305;
pub const KEYBYTES: usize = xsalsa20poly1305::KEYBYTES;
pub const NONCEBYTES: usize = xsalsa20poly1305::NONCEBYTES;
pub const MACBY... |
pub fn gen_nonce() -> Nonce {
Nonce(secretbox::gen_nonce())
}
pub fn encrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Vec<u8> {
secretbox::seal(
doc,
&nonce.0,
&key.0,
)
}
pub fn decrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Result<Vec<u8>, IndyError> {
secretbox::open(
... | pub fn create_key() -> Key {
Key(secretbox::gen_key())
} | random_line_split |
mut-function-arguments.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 | // except according to those terms.
fn f(mut y: ~int) {
*y = 5;
assert!(*y == 5);
}
fn g() {
let frob: &fn(~int) = |mut q| { *q = 2; assert!(*q == 2); };
let w = ~37;
frob(w);
}
pub fn main() {
let z = ~17;
f(z);
g();
} | // 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 | random_line_split |
mut-function-arguments.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let z = ~17;
f(z);
g();
}
| {
let frob: &fn(~int) = |mut q| { *q = 2; assert!(*q == 2); };
let w = ~37;
frob(w);
} | identifier_body |
mut-function-arguments.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (mut y: ~int) {
*y = 5;
assert!(*y == 5);
}
fn g() {
let frob: &fn(~int) = |mut q| { *q = 2; assert!(*q == 2); };
let w = ~37;
frob(w);
}
pub fn main() {
let z = ~17;
f(z);
g();
}
| f | identifier_name |
solvers.rs | use super::{Matrix, Trans, RectMat};
use lapack::*;
use factorizations::*;
use matrixerror::MatrixError;
/// Solve Ax = b via LU Factorization.
///
/// # Arguments
///
/// * `Matrix` - Matrix of type f64
///
/// # Example
/// ```
///#[macro_use] extern crate numbers;
///use numbers::Matrix;
/// pub fn main(){
/// let... | }
}
| {
let (a,ipiv) = try!(lufact(a));
let lda = a.row_size;
let n = a.col_size;
let ldb = b.row_size;
let nrhs = b.col_size;
let mut info = 0;
dgetrs(b'N', n, nrhs, &a.elements, lda, &ipiv, &mut b.elements, ldb , &mut info);
match info {
x if x > 0 => Err(MatrixError::LapackComputa... | identifier_body |
solvers.rs | use super::{Matrix, Trans, RectMat};
use lapack::*;
use factorizations::*;
use matrixerror::MatrixError;
/// Solve Ax = b via LU Factorization.
///
/// # Arguments
///
/// * `Matrix` - Matrix of type f64
///
/// # Example
/// ```
///#[macro_use] extern crate numbers;
///use numbers::Matrix;
/// pub fn main(){
/// let... | <T: RectMat>(a : &mut T, b : &mut T) -> Result<T,MatrixError>{
let (a,ipiv) = try!(lufact(a));
let lda = a.row_size;
let n = a.col_size;
let ldb = b.row_size;
let nrhs = b.col_size;
let mut info = 0;
dgetrs(b'N', n, nrhs, &a.elements, lda, &ipiv, &mut b.elements, ldb, &mut info);
matc... | lusolve | identifier_name |
solvers.rs | use super::{Matrix, Trans, RectMat};
use lapack::*;
use factorizations::*;
use matrixerror::MatrixError;
/// Solve Ax = b via LU Factorization.
///
/// # Arguments
///
/// * `Matrix` - Matrix of type f64
///
/// # Example
/// ```
///#[macro_use] extern crate numbers;
///use numbers::Matrix;
/// pub fn main(){
/// let... |
dgetrs(b'N', n, nrhs, &a.elements, lda, &ipiv, &mut b.elements, ldb, &mut info);
match info {
x if x > 0 => Err(MatrixError::LapackComputationError),
0 => Ok(Matrix {
elements : b.elements.to_owned(),
row_size : ldb,
col_size : nrhs,
transpose : ... | let mut info = 0; | random_line_split |
method-trait-object-with-hrtb.rs | // build-pass (FIXME(62277): could be check-pass?)
// Check that method probing ObjectCandidate works in the presence of
// auto traits and/or HRTBs.
mod internal {
pub trait MyObject<'a> {
type Output;
fn foo(&self) -> Self::Output;
}
impl<'a> MyObject<'a> for () {
type Output =... | fn t4(d: &(dyn internal::MyObject<'static, Output=&'static u32> + Sync)) {
d.foo();
}
fn main() {
t1(&());
t2(&());
t3(&());
t4(&());
} |
fn t3(d: &(dyn for<'a> internal::MyObject<'a, Output=&'a u32> + Sync)) {
d.foo();
}
| random_line_split |
method-trait-object-with-hrtb.rs | // build-pass (FIXME(62277): could be check-pass?)
// Check that method probing ObjectCandidate works in the presence of
// auto traits and/or HRTBs.
mod internal {
pub trait MyObject<'a> {
type Output;
fn foo(&self) -> Self::Output;
}
impl<'a> MyObject<'a> for () {
type Output =... | (&self) -> Self::Output { &4 }
}
}
fn t1(d: &dyn for<'a> internal::MyObject<'a, Output=&'a u32>) {
d.foo();
}
fn t2(d: &dyn internal::MyObject<'static, Output=&'static u32>) {
d.foo();
}
fn t3(d: &(dyn for<'a> internal::MyObject<'a, Output=&'a u32> + Sync)) {
d.foo();
}
fn t4(d: &(dyn internal::MyOb... | foo | identifier_name |
method-trait-object-with-hrtb.rs | // build-pass (FIXME(62277): could be check-pass?)
// Check that method probing ObjectCandidate works in the presence of
// auto traits and/or HRTBs.
mod internal {
pub trait MyObject<'a> {
type Output;
fn foo(&self) -> Self::Output;
}
impl<'a> MyObject<'a> for () {
type Output =... |
fn main() {
t1(&());
t2(&());
t3(&());
t4(&());
}
| {
d.foo();
} | identifier_body |
connection.rs | use std::{
fmt::Display,
io::{self, BufRead, BufReader, Write},
net::ToSocketAddrs,
time::Duration,
};
use super::{ClientCodec, NetworkStream, TlsParameters};
use crate::{
address::Envelope,
transport::smtp::{
authentication::{Credentials, Mechanism},
commands::*,
error,... | }
} | }
}
Err(error::response("incomplete response")) | random_line_split |
connection.rs | use std::{
fmt::Display,
io::{self, BufRead, BufReader, Write},
net::ToSocketAddrs,
time::Duration,
};
use super::{ClientCodec, NetworkStream, TlsParameters};
use crate::{
address::Envelope,
transport::smtp::{
authentication::{Credentials, Mechanism},
commands::*,
error,... | }
if challenges == 0 {
Err(error::response("Unexpected number of challenges"))
} else {
Ok(response)
}
}
/// Sends the message content
pub fn message(&mut self, message: &[u8]) -> Result<Response, Error> {
let mut out_buf: Vec<u8> = vec![];
... | {
let mechanism = self
.server_info
.get_auth_mechanism(mechanisms)
.ok_or_else(|| error::client("No compatible authentication mechanism was found"))?;
// Limit challenges to avoid blocking
let mut challenges = 10;
let mut response = self.command(Auth... | identifier_body |
connection.rs | use std::{
fmt::Display,
io::{self, BufRead, BufReader, Write},
net::ToSocketAddrs,
time::Duration,
};
use super::{ClientCodec, NetworkStream, TlsParameters};
use crate::{
address::Envelope,
transport::smtp::{
authentication::{Credentials, Mechanism},
commands::*,
error,... | (&mut self, message: &[u8]) -> Result<Response, Error> {
let mut out_buf: Vec<u8> = vec![];
let mut codec = ClientCodec::new();
codec.encode(message, &mut out_buf);
self.write(out_buf.as_slice())?;
self.write(b"\r\n.\r\n")?;
self.read_response()
}
/// Sends an SM... | message | identifier_name |
dropck_tarena_unsound_drop.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 ... | <'a>(_arena: &'a TypedArena<C<'a>>) {}
fn main() {
let arena: TypedArena<C> = TypedArena::new();
f(&arena); //~ ERROR `arena` does not live long enough
}
| f | identifier_name |
dropck_tarena_unsound_drop.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 ... | struct CheckId<T:HasId> { v: T }
// In the code below, the impl of HasId for `&'a usize` does not
// actually access the borrowed data, but the point is that the
// interface to CheckId does not (and cannot) know that, and therefore
// when encountering the a value V of type CheckId<S>, we must
// conservatively force... |
trait HasId { fn count(&self) -> usize; }
| random_line_split |
class-attributes-2.rs | // Copyright 2012 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct cat {
name... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
class-attributes-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let _kitty = cat(~"Spotty");
} | identifier_body | |
class-attributes-2.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 ... | (name: ~str) -> cat {
cat {
name: name
}
}
pub fn main() {
let _kitty = cat(~"Spotty");
}
| cat | identifier_name |
borrowck-move-subcomponent.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
let a : S = S { x : box 1 };
let pb = &a;
let S { x: ax } = a; //~ ERROR cannot move out
f(pb);
} | identifier_body | |
borrowck-move-subcomponent.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | let S { x: ax } = a; //~ ERROR cannot move out
f(pb);
} | let a : S = S { x : box 1 };
let pb = &a; | random_line_split |
borrowck-move-subcomponent.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let a : S = S { x : box 1 };
let pb = &a;
let S { x: ax } = a; //~ ERROR cannot move out
f(pb);
}
| main | identifier_name |
vlayout.rs | use core::position::{Size, Pos, HasSize, HasPosition};
use core::cellbuffer::CellAccessor;
use std::boxed::Box;
use std::collections::HashMap;
use ui::core::{
Layout,
Alignable,
HorizontalAlign,
VerticalAlign,
Widget,
Frame,
Button,
Painter,
ButtonResult
};
/// Hold buttons an... | ///
/// let buttons = vec![b1, b2, b3].into_iter().map(Box::new);
/// let buttons = buttons.map(|x| x as Box<Button>).collect();
///
/// let mut vlayout = VerticalLayout::from_vec(buttons, 1);
/// vlayout.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Bottom, (0,1));
///
/// maindlg.add_layout(vlayout);
//... | /// let mut maindlg = Dialog::new(60, 10);
///
/// let b1 = StdButton::new("Quit", 'q', ButtonResult::Ok);
/// let b2 = StdButton::new("Foo!", 'f', ButtonResult::Custom(1));
/// let b3 = StdButton::new("Bar!", 'b', ButtonResult::Custom(2)); | random_line_split |
vlayout.rs | use core::position::{Size, Pos, HasSize, HasPosition};
use core::cellbuffer::CellAccessor;
use std::boxed::Box;
use std::collections::HashMap;
use ui::core::{
Layout,
Alignable,
HorizontalAlign,
VerticalAlign,
Widget,
Frame,
Button,
Painter,
ButtonResult
};
/// Hold buttons an... |
fn frame(&self) -> &Frame {
&self.frame
}
fn frame_mut(&mut self) -> &mut Frame {
&mut self.frame
}
}
impl Layout for VerticalLayout {
fn align_elems(&mut self) {
let (x, y) = self.origin;
let mut current_y = y;
for widget in self.widgets.iter_mut() {
... | {
self.frame.resize(new_size);
} | identifier_body |
vlayout.rs | use core::position::{Size, Pos, HasSize, HasPosition};
use core::cellbuffer::CellAccessor;
use std::boxed::Box;
use std::collections::HashMap;
use ui::core::{
Layout,
Alignable,
HorizontalAlign,
VerticalAlign,
Widget,
Frame,
Button,
Painter,
ButtonResult
};
/// Hold buttons an... | (widgets: Vec<Box<Button>>, inner_margin: usize) -> VerticalLayout {
let first_origin = widgets.first().unwrap().frame().origin();
let height = widgets.len() + widgets.len() * inner_margin;
let width = widgets.iter().map(|s| s.frame().size().0).max().unwrap();
VerticalLayout {
... | from_vec | identifier_name |
cssstylevalue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods;
use crate::dom::bindings... | {
reflector: Reflector,
value: String,
}
impl CSSStyleValue {
fn new_inherited(value: String) -> CSSStyleValue {
CSSStyleValue {
reflector: Reflector::new(),
value: value,
}
}
pub fn new(global: &GlobalScope, value: String) -> DomRoot<CSSStyleValue> {
... | CSSStyleValue | identifier_name |
cssstylevalue.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods;
use crate::dom::bindings... | value: value,
}
}
pub fn new(global: &GlobalScope, value: String) -> DomRoot<CSSStyleValue> {
reflect_dom_object(Box::new(CSSStyleValue::new_inherited(value)), global, Wrap)
}
}
impl CSSStyleValueMethods for CSSStyleValue {
/// <https://drafts.css-houdini.org/css-typed-om-1... | reflector: Reflector::new(), | random_line_split |
send-email.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message};
use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION};
use structopt::... | println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("From address: {}", &from_address);
println!("Contact list: {}", &contact_list);
println!("Subject: {}", &subject);
println!("Me... | {
tracing_subscriber::fmt::init();
let Opt {
contact_list,
region,
from_address,
message,
subject,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_els... | identifier_body |
send-email.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message};
use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION};
use structopt::... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
send_message(&client, &contact_list, &from_address, &subject, &message).await
}
| {
println!("SES client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("From address: {}", &from_address);
println!("Contact list: {}", &contact_list);
println... | conditional_block |
send-email.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message};
use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION};
use structopt::... | () -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
contact_list,
region,
from_address,
message,
subject,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_pro... | main | identifier_name |
send-email.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_sesv2::model::{Body, Content, Destination, EmailContent, Message};
use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION};
use structopt::... | /// The email address of the sender.
#[structopt(short, long)]
from_address: String,
/// The message of the email.
#[structopt(short, long)]
message: String,
/// The subject of the email.
#[structopt(short, long)]
subject: String,
/// Whether to display additional information.... | random_line_split | |
cache_tests.rs | use std::convert::TryInto;
use std::io::Write;
use std::path::PathBuf;
use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME};
use store::Store;
use tempfile::TempDir;
use testutil::data::TestData;
use testutil::relative_paths;
use workunit_store::WorkunitStore;
use crate::{
CommandRunner as CommandRunnerTrait, Contex... | .as_ref()
.unwrap()
.try_into()
.unwrap();
let removed = store.remove_file(output_child_digest).await.unwrap();
assert!(removed);
assert!(store
.contents_for_directory(output_dir_digest)
.await
.err()
.is_some())
}
// Ensure that we don't fail if we re-run.
let... | random_line_split | |
cache_tests.rs | use std::convert::TryInto;
use std::io::Write;
use std::path::PathBuf;
use sharded_lmdb::{ShardedLmdb, DEFAULT_LEASE_TIME};
use store::Store;
use tempfile::TempDir;
use testutil::data::TestData;
use testutil::relative_paths;
use workunit_store::WorkunitStore;
use crate::{
CommandRunner as CommandRunnerTrait, Contex... | () {
WorkunitStore::setup_for_tests();
let results = run_roundtrip(1).await;
assert_ne!(results.uncached, results.maybe_cached);
assert_eq!(results.uncached.unwrap().exit_code, 1);
assert_eq!(results.maybe_cached.unwrap().exit_code, 127); // aka the return code for file not found
}
#[tokio::test]
async fn re... | failures_not_cached | identifier_name |
main.rs | extern crate glob;
extern crate rustc_serialize;
extern crate rustache;
use std::error::Error;
use std::process;
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use glob::glob;
use rustc_serialize::json::Json;
use std::env;
fn load(path: &Path) -> String {
let display = path.display();
let mu... | (path: &Path, tmpl: &String) {
let s = load(path);
let data = Json::from_str(&s).unwrap();
let rv = rustache::render_text(tmpl, data).unwrap().unwrap();
let output = String::from_utf8(rv).unwrap();
println!("{}", output);
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.... | read | identifier_name |
main.rs | extern crate glob;
extern crate rustc_serialize;
extern crate rustache;
use std::error::Error;
use std::process;
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use glob::glob;
use rustc_serialize::json::Json;
use std::env;
fn load(path: &Path) -> String {
let display = path.display();
let mu... | }
} | Err(e) => println!("{:?}", e)
} | random_line_split |
main.rs | extern crate glob;
extern crate rustc_serialize;
extern crate rustache;
use std::error::Error;
use std::process;
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use glob::glob;
use rustc_serialize::json::Json;
use std::env;
fn load(path: &Path) -> String {
let display = path.display();
let mu... |
fn main() {
let args: Vec<String> = env::args().collect();
if args.len()!= 3 {
println!("Usage: {} template dataPath", args[0]);
process::exit(1);
}
let tmpl = load(Path::new(&args[1]));
let mut data_path = args[2].clone();
if!data_path.ends_with("/") {
data_path.push('... | {
let s = load(path);
let data = Json::from_str(&s).unwrap();
let rv = rustache::render_text(tmpl, data).unwrap().unwrap();
let output = String::from_utf8(rv).unwrap();
println!("{}", output);
} | identifier_body |
regions-early-bound-used-in-type-param.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let b1 = Box { t: &3i };
assert_eq!(add(b1, b1), 6i);
}
| {
*g1.get() + *g2.get()
} | identifier_body |
regions-early-bound-used-in-type-param.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 ... | <T> {
t: T
}
impl<T:Clone> Get<T> for Box<T> {
fn get(&self) -> T {
self.t.clone()
}
}
fn add<'a,G:Get<&'a int>>(g1: G, g2: G) -> int {
*g1.get() + *g2.get()
}
pub fn main() {
let b1 = Box { t: &3i };
assert_eq!(add(b1, b1), 6i);
}
| Box | identifier_name |
regions-early-bound-used-in-type-param.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 ... | } | random_line_split | |
while-prelude-drop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i)!= a { i += 1; }
}
| {
if i > 10 { return a; }
let mut s = String::from_str("hello");
// Ensure s is non-const.
s.push_str("there");
return b(s);
} | identifier_body |
while-prelude-drop.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 ... | (i: int) -> t {
if i > 10 { return a; }
let mut s = String::from_str("hello");
// Ensure s is non-const.
s.push_str("there");
return b(s);
}
pub fn main() {
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i)!= a { i += 1; }
}
| make | identifier_name |
while-prelude-drop.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 ... | while make(i)!= a { i += 1; }
} | let mut i = 0;
// The auto slot for the result of make(i) should not leak. | random_line_split |
while-prelude-drop.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let mut s = String::from_str("hello");
// Ensure s is non-const.
s.push_str("there");
return b(s);
}
pub fn main() {
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i)!= a { i += 1; }
}
| { return a; } | conditional_block |
create.rs | #[macro_use(rotor_compose)] extern crate rotor;
extern crate rotor_tools;
use std::time::{Duration};
use rotor::{Loop, Config, Scope, Response, Void};
use rotor_tools::timer::{IntervalFunc, interval_func};
use rotor_tools::loop_ext::LoopInstanceExt;
#[derive(PartialEq, Eq)]
struct Dummy;
struct Context;
rotor_comp... | <C>(scope: &mut Scope<C>)
-> Response<(IntervalFunc<C>, Dummy), Void>
{
interval_func(scope, Duration::new(1, 0), |_| {
println!("Second passed");
}).wrap(|fsm| (fsm, Dummy))
}
fn main() {
let loop_creator = Loop::new(&Config::new()).unwrap();
let mut loop_inst = loop_creator.instantiate(Co... | create_pair | identifier_name |
create.rs | #[macro_use(rotor_compose)] extern crate rotor;
extern crate rotor_tools;
use std::time::{Duration};
use rotor::{Loop, Config, Scope, Response, Void};
use rotor_tools::timer::{IntervalFunc, interval_func};
use rotor_tools::loop_ext::LoopInstanceExt;
#[derive(PartialEq, Eq)]
struct Dummy;
struct Context;
rotor_comp... | interval_func(scope, Duration::new(1, 0), |_| {
println!("Second passed");
}).wrap(|fsm| (fsm, Dummy))
}
fn main() {
let loop_creator = Loop::new(&Config::new()).unwrap();
let mut loop_inst = loop_creator.instantiate(Context);
let value: Dummy = loop_inst.add_and_fetch(Fsm::Timer, |scope| {... | fn create_pair<C>(scope: &mut Scope<C>)
-> Response<(IntervalFunc<C>, Dummy), Void>
{ | random_line_split |
create.rs | #[macro_use(rotor_compose)] extern crate rotor;
extern crate rotor_tools;
use std::time::{Duration};
use rotor::{Loop, Config, Scope, Response, Void};
use rotor_tools::timer::{IntervalFunc, interval_func};
use rotor_tools::loop_ext::LoopInstanceExt;
#[derive(PartialEq, Eq)]
struct Dummy;
struct Context;
rotor_comp... | {
let loop_creator = Loop::new(&Config::new()).unwrap();
let mut loop_inst = loop_creator.instantiate(Context);
let value: Dummy = loop_inst.add_and_fetch(Fsm::Timer, |scope| {
create_pair(scope)
}).unwrap();
assert!(value == Dummy);
loop_inst.run().unwrap();
} | identifier_body | |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Tests for parsing and serialization of values/properties
use cssparser::Parser;
use media_queries::CSSErrorRe... | ($fun:expr,$input:expr, $output:expr) => {
let mut parser = Parser::new($input);
let parsed = $fun(&mut parser)
.expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
let mut parse... | random_line_split | |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Tests for parsing and serialization of values/properties
use cssparser::Parser;
use media_queries::CSSErrorRe... |
// This is a macro so that the file/line information
// is preserved in the panic
macro_rules! assert_roundtrip_with_context {
($fun:expr, $string:expr) => {
assert_roundtrip_with_context!($fun, $string, $string);
};
($fun:expr,$input:expr, $output:expr) => {
let url = ::servo_url::ServoUr... | {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest));
let mut parser = Parser::new(s);
f(&context, &mut parser)
} | identifier_body |
mod.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Tests for parsing and serialization of values/properties
use cssparser::Parser;
use media_queries::CSSErrorRe... | <T, F: Fn(&ParserContext, &mut Parser) -> Result<T, ()>>(f: F, s: &str) -> Result<T, ()> {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest));
let mut parser = Parser::new(s);
f(&context, &mut parser... | parse | identifier_name |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
let span = variant.span;
// expr for `$n == $variant as $name`
let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
let variant = cx.expr_path(path);
let ty = cx.ty_ident(span, cx.i... | {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
Inter... | conditional_block |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::num::FromPrimitive),
additional_bounds: Vec::new(),
generics: Lifetim... | { | random_line_split |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | attributes: attrs.clone(),
combine_substructure: combine_substructure(box |c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
... | {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::num::FromPrimitive),
additional_bounds: Vec::new(),
generics: Lifet... | identifier_body |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <F>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
let inline = cx.meta_word(span, InternedString... | expand_deriving_from_primitive | identifier_name |
string.rs | extern crate llvm_sys;
use codegen::llvm::core::{Builder, Context, Module, Type};
use self::llvm_sys::LLVMIntPredicate; // TODO: Remove
// TODO: Change to put string def in module if not already there
// use std.string.String
pub fn string_type(context: &Context) -> Type {
let field_types = vec![
context.... | context.struct_type(field_types)
}
// TODO: Move out of the string file:
pub fn print_function_definition(builder: &Builder, context: &Context, module: &Module) {
// Types
let void = context.void_type();
let i32_type = context.i32_type();
let i64_type = context.i64_type();
let i32_ptr_type = i3... | ];
| random_line_split |
string.rs | extern crate llvm_sys;
use codegen::llvm::core::{Builder, Context, Module, Type};
use self::llvm_sys::LLVMIntPredicate; // TODO: Remove
// TODO: Change to put string def in module if not already there
// use std.string.String
pub fn string_type(context: &Context) -> Type |
// TODO: Move out of the string file:
pub fn print_function_definition(builder: &Builder, context: &Context, module: &Module) {
// Types
let void = context.void_type();
let i32_type = context.i32_type();
let i64_type = context.i64_type();
let i32_ptr_type = i32_type.ptr_type(0);
let string_typ... | {
let field_types = vec![
context.i8_type().ptr_type(0),
context.i64_type(), // len
context.i64_type(), // cap
];
context.struct_type(field_types)
} | identifier_body |
string.rs | extern crate llvm_sys;
use codegen::llvm::core::{Builder, Context, Module, Type};
use self::llvm_sys::LLVMIntPredicate; // TODO: Remove
// TODO: Change to put string def in module if not already there
// use std.string.String
pub fn string_type(context: &Context) -> Type {
let field_types = vec![
context.... | (builder: &Builder, context: &Context, module: &Module) {
// Types
let void = context.void_type();
let i32_type = context.i32_type();
let i64_type = context.i64_type();
let i32_ptr_type = i32_type.ptr_type(0);
let string_type_ptr = string_type(context).ptr_type(0);
let mut args = vec![strin... | print_function_definition | identifier_name |
logger.rs | use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError};
pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{
use log;
log::set_logger(|filter|{
filter.set(level.to_log_level_filter());
Box::new(Logger(level))
})
}
pub fn setup_default() -> Result<(), SetLoggerError> |
pub struct Logger(LogLevel);
impl Log for Logger{
fn enabled(&self, metadata: &LogMetadata) -> bool{
metadata.level() <= self.0
}
fn log(&self, record: &LogRecord){
if self.enabled(record.metadata()){
let location = record.location();
// Get the filename from the location
use std::path::Path;
let ... | {
setup(LogLevel::Debug)
} | identifier_body |
logger.rs | use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError};
pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{
use log;
log::set_logger(|filter|{
filter.set(level.to_log_level_filter());
Box::new(Logger(level))
})
}
pub fn setup_default() -> Result<(), SetLoggerError>{
setup(LogLevel::Debug)
}... | (LogLevel);
impl Log for Logger{
fn enabled(&self, metadata: &LogMetadata) -> bool{
metadata.level() <= self.0
}
fn log(&self, record: &LogRecord){
if self.enabled(record.metadata()){
let location = record.location();
// Get the filename from the location
use std::path::Path;
let filename = Path::ne... | Logger | identifier_name |
logger.rs | use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError};
pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{
use log;
log::set_logger(|filter|{
filter.set(level.to_log_level_filter());
Box::new(Logger(level))
})
}
pub fn setup_default() -> Result<(), SetLoggerError>{
setup(LogLevel::Debug)
}... | }
}
} | random_line_split | |
logger.rs | use log::{Log, LogRecord, LogLevel, LogMetadata, SetLoggerError};
pub fn setup(level: LogLevel) -> Result<(), SetLoggerError>{
use log;
log::set_logger(|filter|{
filter.set(level.to_log_level_filter());
Box::new(Logger(level))
})
}
pub fn setup_default() -> Result<(), SetLoggerError>{
setup(LogLevel::Debug)
}... |
}
}
| {
let location = record.location();
// Get the filename from the location
use std::path::Path;
let filename = Path::new(record.location().file()).file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or(String::from("Unknown location"));
println!("[{:?}][{2}:{3}][{1}] {4}", record.level(), locat... | conditional_block |
navigator.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::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::Na... | () -> Navigator {
Navigator {
reflector_: Reflector::new(),
bluetooth: Default::default(),
plugins: Default::default(),
mime_types: Default::default(),
service_worker: Default::default(),
vr: Default::default(),
permissions: Def... | new_inherited | identifier_name |
navigator.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::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::Na... | }
// https://html.spec.whatwg.org/multipage/#dom-navigator-plugins
fn Plugins(&self) -> Root<PluginArray> {
self.plugins.or_init(|| PluginArray::new(&self.global()))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes
fn MimeTypes(&self) -> Root<MimeTypeArray> {
... | random_line_split | |
navigator.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::NavigatorBinding;
use dom::bindings::codegen::Bindings::NavigatorBinding::Na... |
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled
fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://h... | {
navigatorinfo::Product()
} | identifier_body |
borrowck-preserve-box-in-field.rs | // xfail-pretty
// 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
//... | {
let mut x = @F {f: ~3};
borrow(x.f, |b_x| {
assert_eq!(*b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x)));
x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(*b_x)) as uint);
assert_eq!(*b_x, 3);
... | identifier_body | |
borrowck-preserve-box-in-field.rs | // xfail-pretty
// 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
//... | () {
let mut x = @F {f: ~3};
borrow(x.f, |b_x| {
assert_eq!(*b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x)));
x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(*b_x)) as uint);
assert_eq!(*b_x, 3);
... | main | identifier_name |
borrowck-preserve-box-in-field.rs | // xfail-pretty
// 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
//... | f(x);
let after = *x;
assert_eq!(before, after);
}
struct F { f: ~int }
pub fn main() {
let mut x = @F {f: ~3};
borrow(x.f, |b_x| {
assert_eq!(*b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x)));
x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(... |
fn borrow(x: &int, f: |x: &int|) {
let before = *x; | random_line_split |
block_add.rs | /// Implements the block_add procedure
/*
Block storing is a tricky part; blocks are stored in the spend-tree and referenced in the
hash-index
This can go out of order: For instance consider 5 blocks added in the order A, B, D, E, C
(for this pseudocode, each block has the previous letter as prev_block_hash)
... |
// we couldn't add this block to the index, which means some block is awaiting connection
let guards = store.block_index.get(conn.block_hash.as_ref());
if guards.iter().any(|ptr|!ptr.is_guard()) {
// this is not a guard, this is _this_ block. This means the block
// wa... | {
trace!(store.logger, "Connect block - set-hash-loop - ok");
continue;
} | conditional_block |
block_add.rs | /// Implements the block_add procedure
/*
Block storing is a tricky part; blocks are stored in the spend-tree and referenced in the
hash-index
This can go out of order: For instance consider 5 blocks added in the order A, B, D, E, C
(for this pseudocode, each block has the previous letter as prev_block_hash)
... | let mut chunk_stats = TransactionStats { cloning: cloning,..Default::default() };
for tx in chunk_tx {
let p1 = Instant::now();
let hash = Hash32Buf::double_sha256(tx.to_raw());
hashes.push(hash);
let p2 = Instant::now();
let res = tx.... | {
let timer = ::std::time::Instant::now();
// We use chunked parallelization because otherwise we need to clone() the stores on each
// iteration
// The main procedure here is to hash and call verify_and_store for each transaction
let chunks: Vec<_> =
block.txs.par_chunks(PARALLEL_HASHING_... | identifier_body |
block_add.rs | /// Implements the block_add procedure
/*
Block storing is a tricky part; blocks are stored in the spend-tree and referenced in the
hash-index
This can go out of order: For instance consider 5 blocks added in the order A, B, D, E, C
(for this pseudocode, each block has the previous letter as prev_block_hash)
... |
}
} | add_block(&mut store, &block2);
add_block(&mut store, &block1); | random_line_split |
block_add.rs | /// Implements the block_add procedure
/*
Block storing is a tricky part; blocks are stored in the spend-tree and referenced in the
hash-index
This can go out of order: For instance consider 5 blocks added in the order A, B, D, E, C
(for this pseudocode, each block has the previous letter as prev_block_hash)
... | { data: Vec<u32> };
impl Clone for X {
fn clone(&self) -> X { X { data: self.data.clone() } }
}
let x = X { data: vec![1,2,3,4,5,6,7,8,9,10]};
let y = vec![10,11,12,13,14,15,16,17,18,19,20];
y.into_par_iter().map(|z| {
let u = &mut x.clone(); // is this... | X | identifier_name |
run.rs | use super::{Async, Pair, AsyncError, Future};
use syncbox::Task;
use syncbox::TaskBox;
use syncbox::Run;
/// This method defers a task onto a task runner until we can complete that call.
/// Currently we only support using a ThreadPool as the task runner itself.
pub fn | <R: Run<Box<TaskBox>> + Send +'static,
A: Async +'static>(task_runner: R, future_in: A) -> Future<A::Value, A::Error> {
let (complete, future_out) = Future::pair();
complete.receive(|result_or_error| {
if let Ok(complete) = result_or_error {
future_in.receive(move | result_or_er... | defer | identifier_name |
run.rs | use super::{Async, Pair, AsyncError, Future};
use syncbox::Task;
use syncbox::TaskBox;
use syncbox::Run;
/// This method defers a task onto a task runner until we can complete that call.
/// Currently we only support using a ThreadPool as the task runner itself.
pub fn defer<R: Run<Box<TaskBox>> + Send +'static,
... |
/// This method backgrounds a task onto a task runner waiting for complete to be called.
/// Currently we only support using a ThreadPool as the task runner itself.
pub fn background<R: Run<Box<TaskBox>> + Send +'static, F: FnOnce() -> T + Send +'static,
T: Send>(task_runner: R, closure: Box<F>) ->... | {
let (complete, future_out) = Future::pair();
complete.receive(|result_or_error| {
if let Ok(complete) = result_or_error {
future_in.receive(move | result_or_error | {
match result_or_error {
Ok(val) => task_runner.run(Box::new(|| complete.complete(val)))... | identifier_body |
run.rs | use super::{Async, Pair, AsyncError, Future};
use syncbox::Task;
use syncbox::TaskBox;
use syncbox::Run;
/// This method defers a task onto a task runner until we can complete that call.
/// Currently we only support using a ThreadPool as the task runner itself. | pub fn defer<R: Run<Box<TaskBox>> + Send +'static,
A: Async +'static>(task_runner: R, future_in: A) -> Future<A::Value, A::Error> {
let (complete, future_out) = Future::pair();
complete.receive(|result_or_error| {
if let Ok(complete) = result_or_error {
future_in.receive(move | ... | random_line_split | |
lib.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file | //
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software 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 go... | // to you 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 | random_line_split |
util.rs | use libc::{c_int, c_void, setsockopt, socklen_t, timespec};
use std::{io, ptr};
use std::mem::size_of;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// `setsockopt` wrapper
///
/// The libc `setsockopt` function is set to set various options on a socket.
/// `set_socket_option` offers a somewhat type-safe wrapp... |
pub fn set_socket_option_mult<T>(fd: c_int,
level: c_int,
name: c_int,
values: &[T])
-> io::Result<()> {
let rv = if values.len() < 1 {
// can't pass in a pointer to the fir... | {
let rv = unsafe {
let val_ptr: *const T = val as *const T;
setsockopt(fd,
level,
name,
val_ptr as *const c_void,
size_of::<T>() as socklen_t)
};
if rv != 0 {
return Err(io::Error::last_os_error());
}
... | identifier_body |
util.rs | use libc::{c_int, c_void, setsockopt, socklen_t, timespec};
use std::{io, ptr};
use std::mem::size_of;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// `setsockopt` wrapper
///
/// The libc `setsockopt` function is set to set various options on a socket.
/// `set_socket_option` offers a somewhat type-safe wrapp... | <T>(fd: c_int,
level: c_int,
name: c_int,
values: &[T])
-> io::Result<()> {
let rv = if values.len() < 1 {
// can't pass in a pointer to the first element if a 0-length slice,... | set_socket_option_mult | identifier_name |
util.rs | use libc::{c_int, c_void, setsockopt, socklen_t, timespec};
use std::{io, ptr};
use std::mem::size_of;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// `setsockopt` wrapper
///
/// The libc `setsockopt` function is set to set various options on a socket.
/// `set_socket_option` offers a somewhat type-safe wrapp... | else {
unsafe {
let val_ptr = &values[0] as *const T;
setsockopt(fd,
level,
name,
val_ptr as *const c_void,
(size_of::<T>() * values.len()) as socklen_t)
}
};
if rv!= 0 {
... | {
// can't pass in a pointer to the first element if a 0-length slice,
// pass a nullpointer instead
unsafe { setsockopt(fd, level, name, ptr::null(), 0) }
} | conditional_block |
util.rs | use libc::{c_int, c_void, setsockopt, socklen_t, timespec};
use std::{io, ptr};
use std::mem::size_of;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// `setsockopt` wrapper
///
/// The libc `setsockopt` function is set to set various options on a socket.
/// `set_socket_option` offers a somewhat type-safe wrapp... | unsafe {
let val_ptr = &values[0] as *const T;
setsockopt(fd,
level,
name,
val_ptr as *const c_void,
(size_of::<T>() * values.len()) as socklen_t)
}
};
if rv!= 0 {
return... | random_line_split | |
word.rs | use std::fmt;
use std::ops::Index;
//---
#[derive(Debug)]
pub struct Word {
pub raw: String // TODO keep it only visible inside the crate
}
impl Word {
pub fn new(s: &'static str) -> Word {
Word { raw: s.to_string() }
}
}
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> ... | }
} | random_line_split | |
word.rs |
use std::fmt;
use std::ops::Index;
//---
#[derive(Debug)]
pub struct Word {
pub raw: String // TODO keep it only visible inside the crate
}
impl Word {
pub fn | (s: &'static str) -> Word {
Word { raw: s.to_string() }
}
}
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.raw)
}
}
//---
#[derive(Debug)]
pub struct Bucket {
pub words: Vec<Word> // TODO keep it only visible inside the crate
... | new | identifier_name |
performanceobserverentrylist.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::PerformanceObserverEntryListBinding;
us... |
}
| {
self.entries.borrow().get_entries_by_name_and_type(Some(name), entry_type)
} | identifier_body |
performanceobserverentrylist.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::PerformanceObserverEntryListBinding;
us... | (global: &GlobalScope, entries: PerformanceEntryList)
-> DomRoot<PerformanceObserverEntryList> {
let observer_entry_list = PerformanceObserverEntryList::new_inherited(entries);
reflect_dom_object(box observer_entry_list, global, PerformanceObserverEntryListBinding::Wrap)
}
}
impl Performanc... | new | identifier_name |
performanceobserverentrylist.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::PerformanceObserverEntryListBinding;
us... | }
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope, entries: PerformanceEntryList)
-> DomRoot<PerformanceObserverEntryList> {
let observer_entry_list = PerformanceObserverEntryList::new_inherited(entries);
reflect_dom_object(box observer_entry_list, global, PerformanceOb... | fn new_inherited(entries: PerformanceEntryList) -> PerformanceObserverEntryList {
PerformanceObserverEntryList {
reflector_: Reflector::new(),
entries: DomRefCell::new(entries),
} | random_line_split |
fixed.rs | // Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::translate::*;
use Fixed;
use IsA;
use Value;
use Widget;
/... | <T: IsA<Widget>>(&self, item: &T) -> i32 {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0 as *mut _, item.as_ref().to_glib_none().0, "y".to_glib_none(... | get_child_y | identifier_name |
fixed.rs | // Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::translate::*;
use Fixed;
use IsA;
use Value;
use Widget;
/... | impl<O: IsA<Fixed>> FixedExtManual for O {
fn get_child_x<T: IsA<Widget>>(&self, item: &T) -> i32 {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0... | fn get_child_y<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_child_y<T: IsA<Widget>>(&self, item: &T, y: i32);
}
| random_line_split |
fixed.rs | // Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::translate::*;
use Fixed;
use IsA;
use Value;
use Widget;
/... |
fn set_child_x<T: IsA<Widget>>(&self, item: &T, x: i32) {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0 as *mut _, item.as_ref().to_glib_none().0, "x".to_glib_none().0, Value::from(&x)... | {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0 as *mut _, item.as_ref().to_glib_none().0, "x".to_glib_none().0, value.to_glib_none_mut().0);
... | identifier_body |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
}
match CString::new(safe) {
Ok(cstr) => cstr,
_ => {
CString::new("<failed to encode string>").unwrap()
}
}
}
| {
safe.push(*c);
} | conditional_block |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | return (c.SCLogMessage)(
level as i32,
to_safe_cstring(filename).as_ptr(),
line,
to_safe_cstring(function).as_ptr(),
code,
to_safe_cstring(message).as_ptr());
}
}
// Fall back if the Suricata C c... | random_line_split | |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {
let mut safe = Vec::with_capacity(val.len());
for c in val.as_bytes() {
if *c != 0 {
safe.push(*c);
}
}
match CString::new(safe) {
Ok(cstr) => cstr,
_ => {
CString::new("<failed to encode string>").unwrap()
}
}
} | identifier_body | |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | (val: &str) -> CString {
let mut safe = Vec::with_capacity(val.len());
for c in val.as_bytes() {
if *c!= 0 {
safe.push(*c);
}
}
match CString::new(safe) {
Ok(cstr) => cstr,
_ => {
CString::new("<failed to encode string>").unwrap()
}
}
}... | to_safe_cstring | identifier_name |
search.rs | use std::io;
use std::collections::HashMap;
use asnom::structure::StructureTag;
use asnom::structures::{Tag, Sequence, Integer, OctetString, Boolean};
use asnom::common::TagClass::*;
use rfc4515::parse;
use futures::{Future, stream, Stream};
use tokio_service::Service;
use ldap::Ldap;
use service::{LdapMessage, Lda... | .map(|v| String::from_utf8(v).unwrap())
.collect();
let key = inner.pop().unwrap();
let keystr = String::from_utf8(key.expect_primitive().unwrap()).unwrap();
map.insert(keystr, valuev);
}
Some(map)
}
impl Ldap {
pub fn search(&se... | .into_iter()
.map(|t| t.expect_primitive().unwrap()) | random_line_split |
search.rs | use std::io;
use std::collections::HashMap;
use asnom::structure::StructureTag;
use asnom::structures::{Tag, Sequence, Integer, OctetString, Boolean};
use asnom::common::TagClass::*;
use rfc4515::parse;
use futures::{Future, stream, Stream};
use tokio_service::Service;
use ldap::Ldap;
use service::{LdapMessage, Lda... | {
Reference(Vec<String>),
Object {
object_name: String,
attributes: HashMap<String, Vec<String>>,
},
}
impl SearchEntry {
pub fn construct(tag: Tag) -> SearchEntry {
match tag {
Tag::StructureTag(t) => {
match t.id {
// Search Res... | SearchEntry | identifier_name |
pin-unsound-issue-66544-clone.rs | use std::cell::Cell;
use std::marker::PhantomPinned;
use std::pin::Pin;
struct | <'a>(Cell<Option<&'a mut MyType<'a>>>, PhantomPinned);
impl<'a> Clone for &'a mut MyType<'a> {
//~^ ERROR E0751
fn clone(&self) -> &'a mut MyType<'a> {
self.0.take().unwrap()
}
}
fn main() {
let mut unpinned = MyType(Cell::new(None), PhantomPinned);
let bad_addr = &unpinned as *const MyTyp... | MyType | identifier_name |
pin-unsound-issue-66544-clone.rs | use std::cell::Cell;
use std::marker::PhantomPinned;
use std::pin::Pin;
| impl<'a> Clone for &'a mut MyType<'a> {
//~^ ERROR E0751
fn clone(&self) -> &'a mut MyType<'a> {
self.0.take().unwrap()
}
}
fn main() {
let mut unpinned = MyType(Cell::new(None), PhantomPinned);
let bad_addr = &unpinned as *const MyType<'_> as usize;
let mut p = Box::pin(MyType(Cell::ne... | struct MyType<'a>(Cell<Option<&'a mut MyType<'a>>>, PhantomPinned);
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.