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 |
|---|---|---|---|---|
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
#[cfg(feature = "js_backtrace")]
use crate::dom::bindings:... |
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(
self,
cx: *mut JSContext,
global: &GlobalScope,
rval: MutableHandleValue,
) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, s... | {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!(
"\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id)
);
throw_type_error(cx, &error);
} | identifier_body |
controller.rs | pub struct Controller<T: PartialEq> {
pub dpad: DPad<T>,
}
impl<T: PartialEq> Controller<T> {
pub fn new(up: T, left: T, down: T, right: T) -> Controller<T> {
Controller {
dpad: DPad::new(up, left, down, right),
}
}
pub fn down(&mut self, key: &T) {
self.dpad.down(key);
}
pub fn up(&mut... | else {
(x.powi(2) + y.powi(2)).sqrt()
};
[x / z, y / z]
}
}
| {
1.0
} | conditional_block |
controller.rs | pub struct Controller<T: PartialEq> {
pub dpad: DPad<T>,
}
impl<T: PartialEq> Controller<T> {
pub fn new(up: T, left: T, down: T, right: T) -> Controller<T> {
Controller {
dpad: DPad::new(up, left, down, right),
}
}
pub fn down(&mut self, key: &T) {
self.dpad.down(key);
}
pub fn up(&mut... |
pub fn down(&mut self, key: &T) {
for (idx, bind) in self.bindings.iter().enumerate() {
if key == bind {
self.state[idx] = true;
}
}
}
pub fn up(&mut self, key: &T) {
for (idx, bind) in self.bindings.iter().enumerate() {
if key == bind {
self.state[idx] = false;
... | state: [false; 4],
}
} | random_line_split |
controller.rs | pub struct Controller<T: PartialEq> {
pub dpad: DPad<T>,
}
impl<T: PartialEq> Controller<T> {
pub fn | (up: T, left: T, down: T, right: T) -> Controller<T> {
Controller {
dpad: DPad::new(up, left, down, right),
}
}
pub fn down(&mut self, key: &T) {
self.dpad.down(key);
}
pub fn up(&mut self, key: &T) {
self.dpad.up(key);
}
}
pub struct DPad<T: PartialEq> {
bindings: [T; 4],
state: ... | new | identifier_name |
example.rs | use std::cmp::Ordering::Equal;
use std::collections::HashMap;
enum GameResult {
Win,
Draw,
Loss
}
struct TeamResult {
wins: u32,
draws: u32,
losses: u32,
}
impl TeamResult {
fn new() -> TeamResult {
TeamResult { wins: 0, draws: 0, losses: 0 }
}
fn add_game_result(&mut self... | (input: &str) -> String {
let mut results: HashMap<String, TeamResult> = HashMap::new();
for line in input.to_string().lines() {
let parts: Vec<&str> = line.trim_right().split(';').collect();
if parts.len()!= 3 { continue; }
let team1 = parts[0];
let team2 = parts[1];
let... | tally | identifier_name |
example.rs | use std::cmp::Ordering::Equal;
use std::collections::HashMap;
enum GameResult {
Win,
Draw,
Loss
}
struct TeamResult {
wins: u32,
draws: u32,
losses: u32,
}
impl TeamResult {
fn new() -> TeamResult {
TeamResult { wins: 0, draws: 0, losses: 0 }
}
fn add_game_result(&mut self... | let mut results: HashMap<String, TeamResult> = HashMap::new();
for line in input.to_string().lines() {
let parts: Vec<&str> = line.trim_right().split(';').collect();
if parts.len()!= 3 { continue; }
let team1 = parts[0];
let team2 = parts[1];
let outcome = parts[2];
... |
pub fn tally(input: &str) -> String { | random_line_split |
main.rs | use bitmap::Image;
// see read_ppm implementation in the bitmap library
pub fn main() {
// read a PPM image, which was produced by the write-a-ppm-file task
let image = Image::read_ppm("./test_image.ppm").unwrap();
println!("Read using nom parsing:");
println!("Format: {:?}", image.format); | mod tests {
extern crate rand;
use bitmap::{Color, Image};
use std::env;
#[test]
fn read_ppm() {
let mut image = Image::new(2, 1);
image[(0, 0)] = Color {
red: 255,
green: 0,
blue: 0,
};
image[(1, 0)] = Color {
red: 0,
... | println!("Dimensions: {} x {}", image.height, image.width);
}
#[cfg(test)] | random_line_split |
main.rs | use bitmap::Image;
// see read_ppm implementation in the bitmap library
pub fn main() |
#[cfg(test)]
mod tests {
extern crate rand;
use bitmap::{Color, Image};
use std::env;
#[test]
fn read_ppm() {
let mut image = Image::new(2, 1);
image[(0, 0)] = Color {
red: 255,
green: 0,
blue: 0,
};
image[(1, 0)] = Color {
... | {
// read a PPM image, which was produced by the write-a-ppm-file task
let image = Image::read_ppm("./test_image.ppm").unwrap();
println!("Read using nom parsing:");
println!("Format: {:?}", image.format);
println!("Dimensions: {} x {}", image.height, image.width);
} | identifier_body |
main.rs | use bitmap::Image;
// see read_ppm implementation in the bitmap library
pub fn main() {
// read a PPM image, which was produced by the write-a-ppm-file task
let image = Image::read_ppm("./test_image.ppm").unwrap();
println!("Read using nom parsing:");
println!("Format: {:?}", image.format);
print... | () {
let mut image = Image::new(2, 1);
image[(0, 0)] = Color {
red: 255,
green: 0,
blue: 0,
};
image[(1, 0)] = Color {
red: 0,
green: 255,
blue: 0,
};
let fname = format!(
"{}/test-{}.ppm... | read_ppm | identifier_name |
lib.rs | pub mod one;
pub mod two;
pub mod ffigen;
//Integer marshaling
#[no_mangle]
pub extern fn test_u8(p: u8) -> u8 {
p
}
#[no_mangle]
pub extern fn test_u16(p: u16) -> u16 {
p
}
#[no_mangle]
pub extern fn test_u32(p: u32) -> u32 {
p
}
#[no_mangle]
pub extern fn test_i8(p: i8) -> i8 {
p
}
#[no_mangle]... | : f32) -> f32 {
p
}
#[no_mangle]
pub extern fn test_f64(p: f64) -> f64 {
p
}
//Boolean marshaling
#[no_mangle]
pub extern fn test_bool(p: bool) -> bool {
p == true
}
//String marshaling
#[no_mangle]
pub extern fn test_string(p: String) -> String {
p.clone()
}
#[no_mangle]
pub extern fn test_string_r... | st_f32(p | identifier_name |
lib.rs | pub mod one;
pub mod two;
pub mod ffigen;
//Integer marshaling
#[no_mangle]
pub extern fn test_u8(p: u8) -> u8 {
p
}
#[no_mangle]
pub extern fn test_u16(p: u16) -> u16 {
| #[no_mangle]
pub extern fn test_u32(p: u32) -> u32 {
p
}
#[no_mangle]
pub extern fn test_i8(p: i8) -> i8 {
p
}
#[no_mangle]
pub extern fn test_i16(p: i16) -> i16 {
p
}
#[no_mangle]
pub extern fn test_i32(p: i32) -> i32 {
p
}
//Float marshaling
#[no_mangle]
pub extern fn test_f32(p: f32) -> f32 {
... | p
}
| identifier_body |
lib.rs | pub mod one;
pub mod two;
pub mod ffigen;
//Integer marshaling
#[no_mangle]
pub extern fn test_u8(p: u8) -> u8 {
p
}
#[no_mangle]
pub extern fn test_u16(p: u16) -> u16 {
p
}
#[no_mangle]
pub extern fn test_u32(p: u32) -> u32 {
p
}
#[no_mangle]
pub extern fn test_i8(p: i8) -> i8 {
p
}
#[no_mangle]... | p.to_string()
} | random_line_split | |
test_poll.rs | use nix::{
Error,
errno::Errno,
poll::{PollFlags, poll, PollFd},
unistd::{write, pipe}
};
macro_rules! loop_while_eintr {
($poll_expr: expr) => {
loop {
match $poll_expr {
Ok(nfds) => break nfds,
Err(Error::Sys(Errno::EINTR)) => (),
... | write(w, b".").unwrap();
// Poll a readable pipe. Should return an event.
let nfds = poll(&mut fds, 100).unwrap();
assert_eq!(nfds, 1);
assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN));
}
// ppoll(2) is the same as poll except for how it handles timeouts and signals.
// Repeating th... | random_line_split | |
test_poll.rs | use nix::{
Error,
errno::Errno,
poll::{PollFlags, poll, PollFd},
unistd::{write, pipe}
};
macro_rules! loop_while_eintr {
($poll_expr: expr) => {
loop {
match $poll_expr {
Ok(nfds) => break nfds,
Err(Error::Sys(Errno::EINTR)) => (),
... | () {
let (r, w) = pipe().unwrap();
let mut fds = [PollFd::new(r, PollFlags::POLLIN)];
// Poll an idle pipe. Should timeout
let nfds = loop_while_eintr!(poll(&mut fds, 100));
assert_eq!(nfds, 0);
assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN));
write(w, b".").unwrap();
... | test_poll | identifier_name |
test_poll.rs | use nix::{
Error,
errno::Errno,
poll::{PollFlags, poll, PollFd},
unistd::{write, pipe}
};
macro_rules! loop_while_eintr {
($poll_expr: expr) => {
loop {
match $poll_expr {
Ok(nfds) => break nfds,
Err(Error::Sys(Errno::EINTR)) => (),
... |
// ppoll(2) is the same as poll except for how it handles timeouts and signals.
// Repeating the test for poll(2) should be sufficient to check that our
// bindings are correct.
#[cfg(any(target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux"))]
#[test... | {
let (r, w) = pipe().unwrap();
let mut fds = [PollFd::new(r, PollFlags::POLLIN)];
// Poll an idle pipe. Should timeout
let nfds = loop_while_eintr!(poll(&mut fds, 100));
assert_eq!(nfds, 0);
assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN));
write(w, b".").unwrap();
//... | identifier_body |
tag-align-shape.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = {c8: 22u8, t: a_tag(44u64)};
let y = fmt!("%?", x);
debug!("y = %s", y);
assert!(y == "(22, a_tag(44))");
}
| main | identifier_name |
tag-align-shape.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = {c8: 22u8, t: a_tag(44u64)};
let y = fmt!("%?", x);
debug!("y = %s", y);
assert!(y == "(22, a_tag(44))");
} | identifier_body | |
tag-align-shape.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 ... | debug!("y = %s", y);
assert!(y == "(22, a_tag(44))");
} | random_line_split | |
callbacks.rs | use std::panic;
use std::ffi::CStr;
use printf::printf;
use alpm_sys::*;
use libc::{c_int, c_char, c_void, off_t};
use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult};
use event::Event;
/// Function with C calling convention and required type signature to wrap our callback
pub unsafe extern "C"... | */
pub unsafe extern "C" fn alpm_cb_totaldl(total: off_t) {
let total = total as u64;
panic::catch_unwind(|| {
let mut cb = DLTOTAL_CB.lock().unwrap();
if let Some(ref mut cb) = *cb {
cb(total);
}
}).unwrap_or(()) // ignore all errors since we are about to cross ffi boun... | random_line_split | |
callbacks.rs | use std::panic;
use std::ffi::CStr;
use printf::printf;
use alpm_sys::*;
use libc::{c_int, c_char, c_void, off_t};
use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult};
use event::Event;
/// Function with C calling convention and required type signature to wrap our callback
pub unsafe extern "C"... | (total: off_t) {
let total = total as u64;
panic::catch_unwind(|| {
let mut cb = DLTOTAL_CB.lock().unwrap();
if let Some(ref mut cb) = *cb {
cb(total);
}
}).unwrap_or(()) // ignore all errors since we are about to cross ffi boundary
}
/** A callback for downloading files... | alpm_cb_totaldl | identifier_name |
callbacks.rs | use std::panic;
use std::ffi::CStr;
use printf::printf;
use alpm_sys::*;
use libc::{c_int, c_char, c_void, off_t};
use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult};
use event::Event;
/// Function with C calling convention and required type signature to wrap our callback
pub unsafe extern "C"... | {
let evt = Event::new(evt);
panic::catch_unwind(|| {
let mut cb = EVENT_CB.lock().unwrap();
if let Some(ref mut cb) = *cb {
cb(evt);
}
}).unwrap_or(())
} | identifier_body | |
callbacks.rs | use std::panic;
use std::ffi::CStr;
use printf::printf;
use alpm_sys::*;
use libc::{c_int, c_char, c_void, off_t};
use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult};
use event::Event;
/// Function with C calling convention and required type signature to wrap our callback
pub unsafe extern "C"... |
}).unwrap_or(-1) // set error code if we have panicked
}
/** Event callback */
pub unsafe extern "C" fn alpm_cb_event(evt: *const alpm_event_t) {
let evt = Event::new(evt);
panic::catch_unwind(|| {
let mut cb = EVENT_CB.lock().unwrap();
if let Some(ref mut cb) = *cb {
cb(evt);
... | {
-1
} | conditional_block |
entries.rs | use std::env;
use std::error::Error;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use controllers::prelude::*;
use models::{queries, Tag};
use views;
use util;
use aqua_web::plug;
use aqua_web::mw::forms::{MultipartForm, SavedFile};
use aqua_web::mw::router::Router;
use... | }
}
pub fn show_thumb(conn: &mut plug::Conn) {
let file_id = Router::param::<i64>(conn, "id")
.expect("missing route param: id");
match queries::find_entry(conn, file_id) {
Ok(entry) => {
let glob_pattern = glob_for_category("t", &entry.hash);
info!("glob pattern: {... | {
let file_id = Router::param::<i64>(conn, "id")
.expect("missing route param: id");
match queries::find_entry(conn, file_id) {
Ok(entry) => {
let glob_pattern = glob_for_category("f", &entry.hash);
info!("glob pattern: {}", glob_pattern);
let paths = glob(&... | identifier_body |
entries.rs | use std::env;
use std::error::Error;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf}; | use views;
use util;
use aqua_web::plug;
use aqua_web::mw::forms::{MultipartForm, SavedFile};
use aqua_web::mw::router::Router;
use glob::glob;
use image::{self, FilterType, ImageFormat, ImageResult};
use serde_json;
#[derive(Serialize)]
struct TagView {
tags: Vec<Tag>,
}
fn glob_for_category(category: &str, dig... |
use controllers::prelude::*;
use models::{queries, Tag}; | random_line_split |
entries.rs | use std::env;
use std::error::Error;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use controllers::prelude::*;
use models::{queries, Tag};
use views;
use util;
use aqua_web::plug;
use aqua_web::mw::forms::{MultipartForm, SavedFile};
use aqua_web::mw::router::Router;
use... | (conn: &mut plug::Conn) {
// TODO: handle webm, etc.
use models::queries;
// TODO: simpler way to get extensions
let mut form_fields = { conn.req_mut().mut_extensions().pop::<MultipartForm>() };
// NOTE: these are separate b/c we need to hang on to the file ref...
let file_upload = form_fie... | submit | identifier_name |
variable.rs | use std::fmt;
use path::Path;
pub struct | {
name: String,
is_new_declaration: bool,
is_global: bool
}
impl VariableAssignment {
pub fn new(name: String, is_new_declaration: bool, is_global: bool) -> VariableAssignment {
VariableAssignment {
name: name,
is_new_declaration: is_new_declaration,
is_glob... | VariableAssignment | identifier_name |
variable.rs | use std::fmt;
use path::Path;
pub struct VariableAssignment {
name: String,
is_new_declaration: bool,
is_global: bool
}
impl VariableAssignment {
pub fn new(name: String, is_new_declaration: bool, is_global: bool) -> VariableAssignment {
VariableAssignment {
name: name,
... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "var({})", self.name)
}
}
pub struct ReadCount {
target: Path
}
impl ReadCount {
pub fn new(target: Path) -> ReadCount {
ReadCount {
target: target
}
}
pub fn target(&self) -> &Path {
... | random_line_split | |
variable.rs | use std::fmt;
use path::Path;
pub struct VariableAssignment {
name: String,
is_new_declaration: bool,
is_global: bool
}
impl VariableAssignment {
pub fn new(name: String, is_new_declaration: bool, is_global: bool) -> VariableAssignment {
VariableAssignment {
name: name,
... |
pub fn is_new_declaration(&self) -> bool {
self.is_new_declaration
}
pub fn is_global(&self) -> bool {
self.is_global
}
pub fn set_is_global(&mut self, is_global: bool) {
self.is_global = is_global
}
}
impl fmt::Display for VariableAssignment {
fn fmt(&self, f: &... | {
&self.name
} | identifier_body |
fakekms_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | assert!(client.supported(key_uri));
let primitive = client.get_aead(key_uri).unwrap();
let plaintext = b"some data to encrypt";
let aad = b"extra data to authenticate";
let ciphertext = primitive.encrypt(&plaintext[..], &aad[..]).unwrap();
let decrypted = primitive.decry... | random_line_split | |
fakekms_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
#[test]
fn test_invalid_prefix() {
tink_aead::init();
let uri_prefix = "fake-kms://CM2x"; // is not a prefix of KEY_URI
let client = FakeClient::new(uri_prefix).unwrap();
assert!(!client.supported(KEY_URI));
assert!(client.get_aead(KEY_URI).is_err());
}
#[test]
fn test_get_aead_fails_with_bad_key... | {
tink_aead::init();
let uri_prefix = "fake-kms://CM2b"; // is a prefix of KEY_URI
let client = FakeClient::new(uri_prefix).unwrap();
assert!(client.supported(KEY_URI));
let result = client.get_aead(KEY_URI);
assert!(result.is_ok(), "{:?}", result.err());
} | identifier_body |
fakekms_test.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | () {
tink_aead::init();
let uri_prefix = "fake-kms://CM2b"; // is a prefix of KEY_URI
let client = FakeClient::new(uri_prefix).unwrap();
assert!(client.supported(KEY_URI));
let result = client.get_aead(KEY_URI);
assert!(result.is_ok(), "{:?}", result.err());
}
#[test]
fn test_invalid_prefix() {... | test_valid_prefix | identifier_name |
closure.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... |
let tcx = ccx.tcx();
debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
let f = match ty::get(closure_ty).sty {
ty::ty_closure(ref f) => f,
_ => {
ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a closure ty,... | match ccx.closure_bare_wrapper_cache.borrow().find(&fn_ptr) {
Some(&llval) => return llval,
None => {}
} | random_line_split |
closure.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... | <'a>(bcx: &'a Block<'a>,
closure_ty: ty::t,
def: def::Def,
fn_ptr: ValueRef)
-> DatumBlock<'a, Expr> {
let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");... | make_closure_from_bare_fn | identifier_name |
closure.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... | debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx));
let f = match ty::get(closure_ty).sty {
ty::ty_closure(ref f) => f,
_ => {
ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a closure ty, got {}",
... | {
let def_id = match def {
def::DefFn(did, _) | def::DefStaticMethod(did, _, _) |
def::DefVariant(_, did, _) | def::DefStruct(did) => did,
_ => {
ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a statically resolved fn, got \
... | identifier_body |
symmetriccipher.rs | // 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.
extern crate crypto... | () {
let message = "Hello World!";
let mut key: [u8; 32] = [0; 32];
let mut iv: [u8; 16] = [0; 16];
// In a real program, the key and iv may be determined
// using some other mechanism. If a password is to be used
// as a key, an algorithm like PBKDF2, Bcrypt, or Scrypt (all
// supported b... | main | identifier_name |
symmetriccipher.rs | // 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.
extern crate crypto... | BufferResult::BufferUnderflow => break,
BufferResult::BufferOverflow => { }
}
}
Ok(final_result)
}
// Decrypts a buffer with the given key and iv using
// AES-256/CBC/Pkcs encryption.
//
// This function is very similar to encrypt(), so, please reference
// comments in that fun... | match result { | random_line_split |
symmetriccipher.rs | // 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.
extern crate crypto... |
Ok(final_result)
}
fn main() {
let message = "Hello World!";
let mut key: [u8; 32] = [0; 32];
let mut iv: [u8; 16] = [0; 16];
// In a real program, the key and iv may be determined
// using some other mechanism. If a password is to be used
// as a key, an algorithm like PBKDF2, Bcrypt, ... | {
let mut decryptor = aes::cbc_decryptor(
aes::KeySize::KeySize256,
key,
iv,
blockmodes::PkcsPadding);
let mut final_result = Vec::<u8>::new();
let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data);
let mut buffer = [0; 4096];
let mut write... | identifier_body |
webdriver_msg.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/. */
#![allow(missing_docs)]
use cookie::Cookie;
use euclid::default::Rect;
use hyper_serde::Serde;
use ipc_channel::... | pub enum WebDriverScriptCommand {
AddCookie(
#[serde(
deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize"
)]
Cookie<'static>,
IpcSender<Result<(), WebDriverCookieError>>,
),
DeleteCookies(IpcSender<Result<(), Er... | use webdriver::common::{WebElement, WebFrame, WebWindow};
use webdriver::error::ErrorStatus;
#[derive(Debug, Deserialize, Serialize)] | random_line_split |
webdriver_msg.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/. */
#![allow(missing_docs)]
use cookie::Cookie;
use euclid::default::Rect;
use hyper_serde::Serde;
use ipc_channel::... | {
Short(u16),
Element(String),
Parent,
}
#[derive(Debug, Deserialize, Serialize)]
pub enum LoadStatus {
LoadComplete,
LoadTimeout,
}
| WebDriverFrameId | identifier_name |
clickable_cell_renderer.rs | /*
* niepce - npc-fwk/toolkit/clickable_cell_renderer.rs | *
* Copyright (C) 2020 Hubert Figuière
*
* This program 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 later version.
*
* This program is di... | random_line_split | |
borrowck-forbid-static-unsafe-interior.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 ... | <T> {
VariantSafe,
VariantUnsafe(Unsafe<T>)
}
static STATIC1: UnsafeEnum<int> = VariantSafe;
static STATIC2: Unsafe<int> = Unsafe{value: 1, marker1: marker::InvariantType};
static STATIC3: MyUnsafe<int> = MyUnsafe{value: STATIC2};
static STATIC4: &'static Unsafe<int> = &STATIC2;
//~^ ERROR borrow of immutabl... | UnsafeEnum | identifier_name |
borrowck-forbid-static-unsafe-interior.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 a = &STATIC1;
//~^ ERROR borrow of immutable static items with unsafe interior is not allowed
STATIC3.forbidden()
//~^ ERROR borrow of immutable static items with unsafe interior is not allowed
} | static UNSAFE: Unsafe<int> = Unsafe{value: 1, marker1: marker::InvariantType};
static WRAPPED_UNSAFE: Wrap<&'static Unsafe<int>> = Wrap { value: &UNSAFE };
//~^ ERROR borrow of immutable static items with unsafe interior is not allowed | random_line_split |
lib.rs | use std::collections::{HashMap, HashSet};
use elasticlunr::{Index, Language};
use lazy_static::lazy_static;
use config::Config;
use errors::{bail, Result};
use library::{Library, Section};
pub const ELASTICLUNR_JS: &str = include_str!("elasticlunr.min.js");
lazy_static! {
static ref AMMONIA: ammonia::Builder<'s... | }
}
#[cfg(test)]
mod tests {
use super::*;
use config::Config;
#[test]
fn can_build_fields() {
let mut config = Config::default();
let fields = build_fields(&config);
assert_eq!(fields, vec!["title", "body"]);
config.search.include_content = false;
config.... | &fill_index(config, &page.meta.title, &page.meta.description, &page.content),
); | random_line_split |
lib.rs | use std::collections::{HashMap, HashSet};
use elasticlunr::{Index, Language};
use lazy_static::lazy_static;
use config::Config;
use errors::{bail, Result};
use library::{Library, Section};
pub const ELASTICLUNR_JS: &str = include_str!("elasticlunr.min.js");
lazy_static! {
static ref AMMONIA: ammonia::Builder<'s... |
#[test]
fn can_fill_index_description() {
let mut config = Config::default();
config.search.include_description = true;
let title = Some("A title".to_string());
let description = Some("A description".to_string());
let content = "Some content".to_string();
let r... | {
let config = Config::default();
let title = Some("A title".to_string());
let description = Some("A description".to_string());
let content = "Some content".to_string();
let res = fill_index(&config, &title, &description, &content);
assert_eq!(res.len(), 2);
asse... | identifier_body |
lib.rs | use std::collections::{HashMap, HashSet};
use elasticlunr::{Index, Language};
use lazy_static::lazy_static;
use config::Config;
use errors::{bail, Result};
use library::{Library, Section};
pub const ELASTICLUNR_JS: &str = include_str!("elasticlunr.min.js");
lazy_static! {
static ref AMMONIA: ammonia::Builder<'s... | (config: &Config) -> Vec<String> {
let mut fields = vec![];
if config.search.include_title {
fields.push("title".to_owned());
}
if config.search.include_description {
fields.push("description".to_owned());
}
if config.search.include_content {
fields.push("body".to_owned... | build_fields | identifier_name |
lib.rs | use std::collections::{HashMap, HashSet};
use elasticlunr::{Index, Language};
use lazy_static::lazy_static;
use config::Config;
use errors::{bail, Result};
use library::{Library, Section};
pub const ELASTICLUNR_JS: &str = include_str!("elasticlunr.min.js");
lazy_static! {
static ref AMMONIA: ammonia::Builder<'s... |
if config.search.include_content {
fields.push("body".to_owned());
}
fields
}
fn fill_index(
config: &Config,
title: &Option<String>,
description: &Option<String>,
content: &str,
) -> Vec<String> {
let mut row = vec![];
if config.search.include_title {
row.push(t... | {
fields.push("description".to_owned());
} | conditional_block |
mod.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including wi... | // SOFTWARE.
mod component;
pub mod resource;
pub mod render_system;
pub mod system;
mod world;
pub use self::component::*;
pub use self::world::{SystemGroup, WorldPlanner, create_world_planner}; | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | random_line_split |
call.rs | use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
use std::time::Instant;
use prost::Message;
/// A remote procedure call.
///
/// `Call` describes a remote procedure call: the remote service, the method, the required feature
/// flags, the deadline, the request, and the response type. `Call` instances ... | }
impl<Req, Resp> Call<Req, Resp>
where
Req: Message +'static,
Resp: Message + Default,
{
/// Creates a new `Call` instance.
pub fn new(
service: &'static str,
method: &'static str,
request: Arc<Req>,
deadline: Instant,
) -> Call<Req, Resp> {
Call {
... | random_line_split | |
call.rs | use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
use std::time::Instant;
use prost::Message;
/// A remote procedure call.
///
/// `Call` describes a remote procedure call: the remote service, the method, the required feature
/// flags, the deadline, the request, and the response type. `Call` instances ... |
dbg.field("deadline", &self.deadline);
dbg.finish()
}
}
impl<Req, Resp> Clone for Call<Req, Resp>
where
Req: Message +'static,
Resp: Message + Default,
{
fn clone(&self) -> Call<Req, Resp> {
Call {
service: self.service,
method: self.method,
... | {
dbg.field("required_feature_flags", &self.required_feature_flags);
} | conditional_block |
call.rs | use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
use std::time::Instant;
use prost::Message;
/// A remote procedure call.
///
/// `Call` describes a remote procedure call: the remote service, the method, the required feature
/// flags, the deadline, the request, and the response type. `Call` instances ... | (
service: &'static str,
method: &'static str,
request: Arc<Req>,
deadline: Instant,
) -> Call<Req, Resp> {
Call {
service,
method,
required_feature_flags: &[],
deadline,
request,
_marker: PhantomData::de... | new | identifier_name |
call.rs | use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
use std::time::Instant;
use prost::Message;
/// A remote procedure call.
///
/// `Call` describes a remote procedure call: the remote service, the method, the required feature
/// flags, the deadline, the request, and the response type. `Call` instances ... |
/// Returns the call's deadline.
pub fn deadline(&self) -> Instant {
self.deadline
}
/// Retrieves the required feature flags of the call.
pub fn required_feature_flags(&self) -> &'static [u32] {
self.required_feature_flags
}
pub fn set_deadline(&mut self, deadline: Insta... | {
self.method
} | identifier_body |
sujiko.rs | //! Sujiko.
//!
//! https://en.wikipedia.org/wiki/Sujiko
//! https://www.simetric.co.uk/sujiko/index.htm
extern crate puzzle_solver;
use puzzle_solver::{Puzzle,Solution,Val,VarToken};
const SIZE: usize = 3;
type Board = [[Val; SIZE]; SIZE];
fn make_sujiko(board: &Board, tl: Val, tr: Val, bl: Val, br: Val)
-... |
}
}
(sys, vars)
}
fn print_sujiko(dict: &Solution, vars: &Vec<Vec<VarToken>>) {
for y in 0..SIZE {
for x in 0..SIZE {
print!(" {}", dict[vars[y][x]]);
}
println!();
}
}
fn verify_sujiko(dict: &Solution, vars: &Vec<Vec<VarToken>>, expected: &Board) {
fo... | {
sys.set_value(vars[y][x], value);
} | conditional_block |
sujiko.rs | //! Sujiko.
//!
//! https://en.wikipedia.org/wiki/Sujiko
//! https://www.simetric.co.uk/sujiko/index.htm
extern crate puzzle_solver;
use puzzle_solver::{Puzzle,Solution,Val,VarToken};
const SIZE: usize = 3;
type Board = [[Val; SIZE]; SIZE];
fn make_sujiko(board: &Board, tl: Val, tr: Val, bl: Val, br: Val)
-... |
fn verify_sujiko(dict: &Solution, vars: &Vec<Vec<VarToken>>, expected: &Board) {
for y in 0..SIZE {
for x in 0..SIZE {
assert_eq!(dict[vars[y][x]], expected[y][x]);
}
}
}
#[test]
fn sujiko_simetric() {
let puzzle = [ [ 6,0,9 ], [ 0,0,0 ], [ 5,0,0 ] ];
let expected = [ [ ... | {
for y in 0..SIZE {
for x in 0..SIZE {
print!(" {}", dict[vars[y][x]]);
}
println!();
}
} | identifier_body |
sujiko.rs | //! Sujiko.
//!
//! https://en.wikipedia.org/wiki/Sujiko
//! https://www.simetric.co.uk/sujiko/index.htm
extern crate puzzle_solver;
use puzzle_solver::{Puzzle,Solution,Val,VarToken};
const SIZE: usize = 3;
type Board = [[Val; SIZE]; SIZE];
fn make_sujiko(board: &Board, tl: Val, tr: Val, bl: Val, br: Val)
-... | (dict: &Solution, vars: &Vec<Vec<VarToken>>) {
for y in 0..SIZE {
for x in 0..SIZE {
print!(" {}", dict[vars[y][x]]);
}
println!();
}
}
fn verify_sujiko(dict: &Solution, vars: &Vec<Vec<VarToken>>, expected: &Board) {
for y in 0..SIZE {
for x in 0..SIZE {
... | print_sujiko | identifier_name |
sujiko.rs | //! Sujiko.
//!
//! https://en.wikipedia.org/wiki/Sujiko
//! https://www.simetric.co.uk/sujiko/index.htm
extern crate puzzle_solver;
use puzzle_solver::{Puzzle,Solution,Val,VarToken};
const SIZE: usize = 3;
type Board = [[Val; SIZE]; SIZE];
fn make_sujiko(board: &Board, tl: Val, tr: Val, bl: Val, br: Val)
-... | for y in 0..SIZE {
for x in 0..SIZE {
print!(" {}", dict[vars[y][x]]);
}
println!();
}
}
fn verify_sujiko(dict: &Solution, vars: &Vec<Vec<VarToken>>, expected: &Board) {
for y in 0..SIZE {
for x in 0..SIZE {
assert_eq!(dict[vars[y][x]], expected[y][x]... | (sys, vars)
}
fn print_sujiko(dict: &Solution, vars: &Vec<Vec<VarToken>>) { | random_line_split |
urlsearchparams.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::URLSearchParamsBinding;
use dom::bindin... | (global: GlobalRef, init: Option<StringOrURLSearchParams>) -> Fallible<Temporary<URLSearchParams>> {
let usp = URLSearchParams::new(global).root();
match init {
Some(eString(_s)) => {
// XXXManishearth we need to parse the input here
// http://url.spec.whatwg.... | Constructor | identifier_name |
urlsearchparams.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::URLSearchParamsBinding;
use dom::bindin... | Some(eString(_s)) => {
// XXXManishearth we need to parse the input here
// http://url.spec.whatwg.org/#concept-urlencoded-parser
// We can use rust-url's implementation here:
// https://github.com/SimonSapin/rust-url/blob/master/form_urlencode... |
pub fn Constructor(global: GlobalRef, init: Option<StringOrURLSearchParams>) -> Fallible<Temporary<URLSearchParams>> {
let usp = URLSearchParams::new(global).root();
match init { | random_line_split |
urlsearchparams.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::URLSearchParamsBinding;
use dom::bindin... |
fn Get(self, name: DOMString) -> Option<DOMString> {
self.data.borrow().get(&name).map(|v| v[0].clone())
}
fn Has(self, name: DOMString) -> bool {
self.data.borrow().contains_key(&name)
}
fn Set(self, name: DOMString, value: DOMString) {
self.data.borrow_mut().insert(name... | {
self.data.borrow_mut().remove(&name);
self.update_steps();
} | identifier_body |
ambig_impl_2_exe.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... | } //~ NOTE is `uint.me2::me`
fn main() { 1u.me(); } //~ ERROR multiple applicable methods in scope
//~^ NOTE is `ambig_impl_2_lib::uint.me::me`
| { *self } | identifier_body |
ambig_impl_2_exe.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... | }
impl me2 for uint { fn me(&self) -> uint { *self } } //~ NOTE is `uint.me2::me`
fn main() { 1u.me(); } //~ ERROR multiple applicable methods in scope
//~^ NOTE is `ambig_impl_2_lib::uint.me::me` | trait me2 {
fn me(&self) -> uint; | random_line_split |
ambig_impl_2_exe.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... | () { 1u.me(); } //~ ERROR multiple applicable methods in scope
//~^ NOTE is `ambig_impl_2_lib::uint.me::me`
| main | identifier_name |
if-let.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 ... |
if 3i > 4 {
panic!("bad math");
} else if let 1 = 2i {
panic!("bad pattern match");
}
enum Foo {
One,
Two(uint),
Three(String, int)
}
let foo = Foo::Three("three".to_string(), 42i);
if let Foo::One = foo {
panic!("bad pattern match");
} ... | } else {
clause = 4;
}
assert_eq!(clause, 4u); | random_line_split |
if-let.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 x = Some(3i);
if let Some(y) = x {
assert_eq!(y, 3i);
} else {
panic!("if-let panicked");
}
let mut worked = false;
if let Some(_) = x {
worked = true;
}
assert!(worked);
let clause: uint;
if let None = Some("test") {
clause = 1;
} els... | main | identifier_name |
label.rs | use sfml::graphics::{RenderTarget, Text, TextStyle, Color};
use sfml::system::vector2::Vector2f;
use window::Window;
use font::Font;
/// A label (text)
pub struct Label<'a> {
text: Text<'a>,
}
impl<'a> Label<'a> {
/// Create a new label
pub fn new(font: &'a Font) -> Self {
let mut label = Label {... | }
} |
/// Draw the label on a window
pub fn draw(&mut self, window: &mut Window) {
window.to_sfml_window().draw(&mut self.text); | random_line_split |
label.rs | use sfml::graphics::{RenderTarget, Text, TextStyle, Color};
use sfml::system::vector2::Vector2f;
use window::Window;
use font::Font;
/// A label (text)
pub struct Label<'a> {
text: Text<'a>,
}
impl<'a> Label<'a> {
/// Create a new label
pub fn new(font: &'a Font) -> Self {
let mut label = Label {... | (&self) -> (f32, f32) {
let pos = self.text.get_position();
(pos.x, pos.y)
}
/// Set the position of the label
pub fn set(&mut self, (x, y): (f32, f32)) -> &mut Self {
self.x(x);
self.y(y)
}
/// Draw the label on a window
pub fn draw(&mut self, window: &mut Win... | pos | identifier_name |
main.rs | use rooster::rclio::RegularInputOutput;
use std::env::VarError;
use std::path::PathBuf;
const ROOSTER_FILE_ENV_VAR: &'static str = "ROOSTER_FILE";
const ROOSTER_FILE_DEFAULT: &'static str = ".passwords.rooster";
fn get_password_file_path() -> Result<PathBuf, i32> {
// First, look for the ROOSTER_FILE environment ... | .to_os_string()
.into_string()
.map_err(|_| 1)?,
);
file_default.push(ROOSTER_FILE_DEFAULT);
Ok(file_default)
}
Err(VarError::NotUnicode(_)) => Err(1),
}
}
fn main() {
let args = std::env::args().collec... | random_line_split | |
main.rs | use rooster::rclio::RegularInputOutput;
use std::env::VarError;
use std::path::PathBuf;
const ROOSTER_FILE_ENV_VAR: &'static str = "ROOSTER_FILE";
const ROOSTER_FILE_DEFAULT: &'static str = ".passwords.rooster";
fn | () -> Result<PathBuf, i32> {
// First, look for the ROOSTER_FILE environment variable.
match std::env::var(ROOSTER_FILE_ENV_VAR) {
Ok(filename) => Ok(PathBuf::from(filename)),
Err(VarError::NotPresent) => {
// If the environment variable is not there, we'll look in the default locati... | get_password_file_path | identifier_name |
main.rs | use rooster::rclio::RegularInputOutput;
use std::env::VarError;
use std::path::PathBuf;
const ROOSTER_FILE_ENV_VAR: &'static str = "ROOSTER_FILE";
const ROOSTER_FILE_DEFAULT: &'static str = ".passwords.rooster";
fn get_password_file_path() -> Result<PathBuf, i32> | }
fn main() {
let args = std::env::args().collect::<Vec<String>>();
let args_refs = args.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
let rooster_file_path = get_password_file_path().unwrap_or_else(|err| std::process::exit(err));
let stdin = std::io::stdin();
let stdout = std::io::stdout()... | {
// First, look for the ROOSTER_FILE environment variable.
match std::env::var(ROOSTER_FILE_ENV_VAR) {
Ok(filename) => Ok(PathBuf::from(filename)),
Err(VarError::NotPresent) => {
// If the environment variable is not there, we'll look in the default location:
// ~/.passw... | identifier_body |
private-inferred-type-2.rs | // Copyright 2017 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 ... | m::Pub::static_method; //~ ERROR type `m::Priv` is private
ext::Pub::static_method; //~ ERROR type `ext::Priv` is private
} | }
}
fn main() {
m::Pub::get_priv; //~ ERROR type `m::Priv` is private | random_line_split |
private-inferred-type-2.rs | // Copyright 2017 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() {
m::Pub::get_priv; //~ ERROR type `m::Priv` is private
m::Pub::static_method; //~ ERROR type `m::Priv` is private
ext::Pub::static_method; //~ ERROR type `ext::Priv` is private
}
| static_method | identifier_name |
propane.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
#[macro_use]
extern crate bencher;
extern crate rand;
extern crate lumol;
extern crate lumol_input;
use bencher::Bencher;
use rand::Rng;
use lumol::sys::EnergyCache;
use lumol::types::Vector3D;
mod util... | encher: &mut Bencher) {
let mut system = utils::get_system("propane");
let mut cache = EnergyCache::new();
cache.init(&system);
let mut rng = rand::weak_rng();
for molecule in system.molecules().to_owned() {
let delta = Vector3D::new(rng.gen(), rng.gen(), rng.gen());
for i in molecu... | che_move_all_rigid_molecules(b | identifier_name |
propane.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
#[macro_use]
extern crate bencher;
extern crate rand;
extern crate lumol;
extern crate lumol_input;
use bencher::Bencher;
use rand::Rng;
use lumol::sys::EnergyCache;
use lumol::types::Vector3D;
mod util... |
benchmark_group!(energy_computation, energy, forces, virial);
benchmark_group!(monte_carlo_cache, cache_move_particles, cache_move_all_rigid_molecules);
benchmark_main!(energy_computation, monte_carlo_cache);
| let mut system = utils::get_system("propane");
let mut cache = EnergyCache::new();
cache.init(&system);
let mut rng = rand::weak_rng();
for molecule in system.molecules().to_owned() {
let delta = Vector3D::new(rng.gen(), rng.gen(), rng.gen());
for i in molecule {
system[... | identifier_body |
propane.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors — BSD license
#[macro_use]
extern crate bencher;
extern crate rand;
extern crate lumol;
extern crate lumol_input;
use bencher::Bencher;
use rand::Rng;
use lumol::sys::EnergyCache;
use lumol::types::Vector3D;
mod util... |
fn forces(bencher: &mut Bencher) {
let system = utils::get_system("propane");
bencher.iter(||{
let _ = system.forces();
})
}
fn virial(bencher: &mut Bencher) {
let system = utils::get_system("propane");
bencher.iter(||{
let _ = system.virial();
})
}
fn cache_move_particles(ben... | random_line_split | |
main.rs | // For random generation
extern crate rand;
// For fmt::Display
use std::fmt;
// For I/O (stdin, stdout, etc)
use std::io::prelude::*;
use rand::Rng;
/// A simple struct for a board
struct Board {
/// The cells of the board
cells: Vec<bool>,
/// The size of the board
size: usize,
}
// Functions for ... | (&self, rhs: &Board) -> bool {
self.cells == rhs.cells
}
}
// Implement the Display format, used with `print!("{}", &board);`
impl fmt::Display for Board {
// Example output:
// 0 1 2
// 0 0 1 0
// 1 1 0 0
// 2 0 1 1
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/... | eq | identifier_name |
main.rs | // For random generation
extern crate rand;
// For fmt::Display
use std::fmt;
// For I/O (stdin, stdout, etc)
use std::io::prelude::*;
use rand::Rng;
| cells: Vec<bool>,
/// The size of the board
size: usize,
}
// Functions for the Board struct
impl Board {
/// Generate a new, empty board, of size >= 1
///
/// Returns a Board in the "off" state, where all cells are 0.
/// If a size of 0 is given, a Board of size 1 will be created instead.
... | /// A simple struct for a board
struct Board {
/// The cells of the board | random_line_split |
main.rs | // For random generation
extern crate rand;
// For fmt::Display
use std::fmt;
// For I/O (stdin, stdout, etc)
use std::io::prelude::*;
use rand::Rng;
/// A simple struct for a board
struct Board {
/// The cells of the board
cells: Vec<bool>,
/// The size of the board
size: usize,
}
// Functions for ... |
Err(_) => {
println!(
"Error: '{}': Unable to parse row or column number",
input[1..].to_string()
);
continue 'userinput;
}... | {
// If we're within bounds, return the parsed number
if x < size {
x
} else {
println!(
"Error: Must specify a row or column within siz... | conditional_block |
main.rs | // For random generation
extern crate rand;
// For fmt::Display
use std::fmt;
// For I/O (stdin, stdout, etc)
use std::io::prelude::*;
use rand::Rng;
/// A simple struct for a board
struct Board {
/// The cells of the board
cells: Vec<bool>,
/// The size of the board
size: usize,
}
// Functions for ... |
/// Generate a random board
///
/// Returns a Board in a random state.
/// If a size of 0 is given, a Board of size 1 will be created instead.
///
/// ```
/// let target: Board = Board::random(3);
/// ```
fn random<R: Rng>(rng: &mut R, size: usize) -> Board {
// Ensure we m... | {
// Check constraints
if col > self.size {
return false;
}
// Loop through the vector column
for i in 0..self.size {
self.cells[col + i * self.size] = !self.cells[col + i * self.size];
}
true
} | identifier_body |
screenshot.rs | extern crate kiss3d;
extern crate nalgebra as na;
use std::path::Path;
use kiss3d::light::Light;
use kiss3d::window::Window;
use na::{UnitQuaternion, Vector3};
// Based on cube example.
fn main() | }
| {
let mut window = Window::new("Kiss3d: screenshot");
let mut c = window.add_cube(0.2, 0.2, 0.2);
c.set_color(1.0, 0.0, 0.0);
c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.785));
c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle(
&Vector3::x_a... | identifier_body |
screenshot.rs | extern crate kiss3d;
extern crate nalgebra as na;
use std::path::Path;
use kiss3d::light::Light;
use kiss3d::window::Window;
use na::{UnitQuaternion, Vector3};
// Based on cube example.
fn | () {
let mut window = Window::new("Kiss3d: screenshot");
let mut c = window.add_cube(0.2, 0.2, 0.2);
c.set_color(1.0, 0.0, 0.0);
c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.785));
c.prepend_to_local_rotation(&UnitQuaternion::from_axis_angle(
&Vector3::... | main | identifier_name |
screenshot.rs | extern crate kiss3d;
extern crate nalgebra as na;
use std::path::Path;
use kiss3d::light::Light;
use kiss3d::window::Window;
use na::{UnitQuaternion, Vector3};
// Based on cube example.
fn main() {
let mut window = Window::new("Kiss3d: screenshot");
let mut c = window.add_cube(0.2, 0.2, 0.2);
c.set_colo... | while window.render() {
let img = window.snap_image();
let img_path = Path::new("screenshot.png");
img.save(img_path).unwrap();
println!("Screeshot saved to `screenshot.png`");
break;
}
} | ));
window.set_light(Light::StickToCamera);
| random_line_split |
mask.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::relay_directive::RelayDirective;
use graphql_ir::{
FragmentDefinition, FragmentSpread, InlineFragment, OperationDe... | joined_arguments.insert(variable.name.item, variable);
}
for arg in self.current_reachable_arguments.drain(..) {
match joined_arguments.entry(arg.name.item) {
Entry::Vacant(entry) => {
entry.insert(arg);
}
Entry:... | }
fn join_current_arguments_to_fragment(&mut self, fragment: &mut FragmentDefinition) {
let mut joined_arguments = JoinedArguments::default();
for variable in &fragment.used_global_variables { | random_line_split |
mask.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::relay_directive::RelayDirective;
use graphql_ir::{
FragmentDefinition, FragmentSpread, InlineFragment, OperationDe... |
fn transform_fragment(
&mut self,
fragment: &FragmentDefinition,
) -> Transformed<FragmentDefinition> {
let result = self.default_transform_fragment(fragment);
if self.current_reachable_arguments.is_empty() {
result
} else {
Transformed::Replace(... | {
let result = self.default_transform_operation(operation);
self.current_reachable_arguments.clear();
result
} | identifier_body |
mask.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::relay_directive::RelayDirective;
use graphql_ir::{
FragmentDefinition, FragmentSpread, InlineFragment, OperationDe... |
}
}
}
let range = RangeFull;
fragment.used_global_variables = joined_arguments
.drain(range)
.map(|(_, v)| v)
.cloned()
.collect();
}
}
impl<'s> Transformer for Mask<'s> {
const NAME: &'static str = "MaskTransform"... | {
entry.insert(arg);
} | conditional_block |
mask.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::relay_directive::RelayDirective;
use graphql_ir::{
FragmentDefinition, FragmentSpread, InlineFragment, OperationDe... | (&mut self, fragment: &mut FragmentDefinition) {
let mut joined_arguments = JoinedArguments::default();
for variable in &fragment.used_global_variables {
joined_arguments.insert(variable.name.item, variable);
}
for arg in self.current_reachable_arguments.drain(..) {
... | join_current_arguments_to_fragment | identifier_name |
word2vec.rs |
extern crate vect;
extern crate argparse;
use vect::termcounts;
use vect::ingestion;
use vect::dictionary::Dictionary;
use argparse::{ArgumentParser, Store};
use vect::huffman;
use vect::base::split_words;
use std::io;
// This is labeled public to shut up the linter about dead code
pub fn main() {
let mut input_f... | {
for line in try!(ingestion::ingest_lines(&input_filename)) {
let line = try!(line);
let words = split_words(&line);
for i in 0..words.len()-1 {
dictionary.update_both(&words[i], &words[i+1]);
}
}
Ok(())
} | identifier_body | |
word2vec.rs | extern crate vect;
extern crate argparse;
use vect::termcounts;
use vect::ingestion;
use vect::dictionary::Dictionary;
use argparse::{ArgumentParser, Store};
use vect::huffman;
use vect::base::split_words;
use std::io;
| // This is labeled public to shut up the linter about dead code
pub fn main() {
let mut input_filename = "word2vec_input".to_string();
let mut output_filename = "word2vec_termcounts".to_string();
{ // Limit the scope of ap.refer()
let mut ap = ArgumentParser::new();
ap.set_description("Crea... | random_line_split | |
word2vec.rs |
extern crate vect;
extern crate argparse;
use vect::termcounts;
use vect::ingestion;
use vect::dictionary::Dictionary;
use argparse::{ArgumentParser, Store};
use vect::huffman;
use vect::base::split_words;
use std::io;
// This is labeled public to shut up the linter about dead code
pub fn main() {
let mut input_f... | (dictionary: &mut Dictionary, input_filename: &str) -> io::Result<()> {
for line in try!(ingestion::ingest_lines(&input_filename)) {
let line = try!(line);
let words = split_words(&line);
for i in 0..words.len()-1 {
dictionary.update_both(&words[i], &words[i+1]);
}
}
... | train | identifier_name |
arbitrary_self_types_pointers_and_wrappers.rs | // run-pass
#![feature(arbitrary_self_types, unsize, coerce_unsized, dispatch_from_dyn)]
#![feature(rustc_attrs)]
use std::{
ops::{Deref, CoerceUnsized, DispatchFromDyn},
marker::Unsize,
};
struct Ptr<T:?Sized>(Box<T>);
impl<T:?Sized> Deref for Ptr<T> {
type Target = T;
fn deref(&self) -> &T {
... | } | random_line_split | |
arbitrary_self_types_pointers_and_wrappers.rs | // run-pass
#![feature(arbitrary_self_types, unsize, coerce_unsized, dispatch_from_dyn)]
#![feature(rustc_attrs)]
use std::{
ops::{Deref, CoerceUnsized, DispatchFromDyn},
marker::Unsize,
};
struct Ptr<T:?Sized>(Box<T>);
impl<T:?Sized> Deref for Ptr<T> {
type Target = T;
fn deref(&self) -> &T |
}
impl<T: Unsize<U> +?Sized, U:?Sized> CoerceUnsized<Ptr<U>> for Ptr<T> {}
impl<T: Unsize<U> +?Sized, U:?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T> {}
struct Wrapper<T:?Sized>(T);
impl<T:?Sized> Deref for Wrapper<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: CoerceUnsized<U>... | {
&*self.0
} | identifier_body |
arbitrary_self_types_pointers_and_wrappers.rs | // run-pass
#![feature(arbitrary_self_types, unsize, coerce_unsized, dispatch_from_dyn)]
#![feature(rustc_attrs)]
use std::{
ops::{Deref, CoerceUnsized, DispatchFromDyn},
marker::Unsize,
};
struct Ptr<T:?Sized>(Box<T>);
impl<T:?Sized> Deref for Ptr<T> {
type Target = T;
fn deref(&self) -> &T {
... | <T:?Sized>(T);
impl<T:?Sized> Deref for Wrapper<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: CoerceUnsized<U>, U> CoerceUnsized<Wrapper<U>> for Wrapper<T> {}
impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T> {}
trait Trait {
// This method isn't ... | Wrapper | identifier_name |
unboxed-closures-by-ref.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 ... | f()
}
fn main() {
let mut x = 0u;
let y = 2u;
call_fn(|&:| assert_eq!(x, 0));
call_fn_mut(|&mut:| x += y);
call_fn_once(|:| x += y);
assert_eq!(x, y * 2);
} | f()
}
fn call_fn_once<F: FnOnce()>(f: F) { | random_line_split |
unboxed-closures-by-ref.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 call_fn_once<F: FnOnce()>(f: F) {
f()
}
fn main() {
let mut x = 0u;
let y = 2u;
call_fn(|&:| assert_eq!(x, 0));
call_fn_mut(|&mut:| x += y);
call_fn_once(|:| x += y);
assert_eq!(x, y * 2);
}
| {
f()
} | identifier_body |
unboxed-closures-by-ref.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 ... | <F: FnMut()>(mut f: F) {
f()
}
fn call_fn_once<F: FnOnce()>(f: F) {
f()
}
fn main() {
let mut x = 0u;
let y = 2u;
call_fn(|&:| assert_eq!(x, 0));
call_fn_mut(|&mut:| x += y);
call_fn_once(|:| x += y);
assert_eq!(x, y * 2);
}
| call_fn_mut | identifier_name |
authserver.rs |
pub struct AuthServer {
cipher: Cipher
}
impl AuthServer {
fn new(cipher: &Cipher) -> AuthServer {
AuthServer {
cipher: cipher
}
}
fn authenticate(&self, auth_string: &Vec<u8>) -> Response {
}
}
impl Receiver for AuthServer {
fn receive(method: &str,... |
fn encode(&self) -> Result<String, err::Error> {
Ok(try!(url::encode(&vec![
("email", &self.email),
("uid", self.uid),
("role", &format!("{:?}", self)])))
}
fn decode(param_string: &str) -> Result<User, err::Error> {
let params = try!(url::decode(&par... | {
User {
email: email.clone(),
uid: uid,
role: role
}
} | identifier_body |
authserver.rs | pub struct AuthServer {
cipher: Cipher
}
impl AuthServer { | fn new(cipher: &Cipher) -> AuthServer {
AuthServer {
cipher: cipher
}
}
fn authenticate(&self, auth_string: &Vec<u8>) -> Response {
}
}
impl Receiver for AuthServer {
fn receive(method: &str, data: &Vec<u8>) -> Response {
match method {
"a... | random_line_split | |
authserver.rs |
pub struct | {
cipher: Cipher
}
impl AuthServer {
fn new(cipher: &Cipher) -> AuthServer {
AuthServer {
cipher: cipher
}
}
fn authenticate(&self, auth_string: &Vec<u8>) -> Response {
}
}
impl Receiver for AuthServer {
fn receive(method: &str, data: &Vec<u8>) -> Res... | AuthServer | identifier_name |
font_collection.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 ... |
extern {
/*
* CTFontCollection.h
*/
static kCTFontCollectionRemoveDuplicatesOption: CFStringRef;
//fn CTFontCollectionCreateCopyWithFontDescriptors(original: CTFontCollectionRef,
// descriptors: CFArrayRef,
// ... | {
unsafe {
TCFType::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames())
}
} | identifier_body |
font_collection.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 ... | () -> CFArray {
unsafe {
TCFType::wrap_under_create_rule(CTFontManagerCopyAvailableFontFamilyNames())
}
}
extern {
/*
* CTFontCollection.h
*/
static kCTFontCollectionRemoveDuplicatesOption: CFStringRef;
//fn CTFontCollectionCreateCopyWithFontDescriptors(original: CTFontCollectio... | get_family_names | identifier_name |
font_collection.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 ... | // this stupid function doesn't actually do any wildcard expansion;
// it just chooses the best match. Use
// CTFontDescriptorCreateMatchingDescriptors instead.
fn CTFontCollectionCreateMatchingFontDescriptors(collection: CTFontCollectionRef) -> CFArrayRef;
fn CTFontCollectionCreateWithFontDescript... | fn CTFontCollectionCreateFromAvailableFonts(options: CFDictionaryRef) -> CTFontCollectionRef; | random_line_split |
font_collection.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 ... |
let matched_descs: CFArray = TCFType::wrap_under_create_rule(matched_descs);
// I suppose one doesn't even need the CTFontCollection object at this point.
// But we stick descriptors into and out of it just to provide a nice wrapper API.
Some(new_from_descriptors(&matched_descs))
}
... | {
return None;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.