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 |
|---|---|---|---|---|
main.rs | const ASCII_A: u8 = b'A';
fn main() {
let msg = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
let key = "VIGENERECIPHER";
let enc = vigenere(msg, key, true);
let dec = vigenere(&enc, key, false);
println!("msg: {}", msg);
println!("key: {}", key);
println!("e... | else {
dec_byte(c, b)
};
output.push(output_byte as char);
}
output
}
fn to_sanitized_bytes(string: &str) -> Vec<u8> {
string
.chars()
.filter(|&c| c.is_alphabetic())
.map(|c| c.to_ascii_uppercase() as u8)
.collect::<Vec<u8>>()
}
fn enc_byte(m: u8,... | {
enc_byte(c, b)
} | conditional_block |
stat.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 dir = TempDir::new_in(&Path::new("."), "").unwrap();
let path = dir.path().join("file");
{
match File::create(&path) {
Err(..) => unreachable!(),
Ok(f) => {
let mut f = f;
for _ in range(0u, 1000) {
f.write(&[0]);
... | main | identifier_name |
stat.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... |
}
}
assert!(path.exists());
assert_eq!(path.stat().unwrap().size, 1000);
}
| {
let mut f = f;
for _ in range(0u, 1000) {
f.write(&[0]);
}
} | conditional_block |
stat.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... | assert!(path.exists());
assert_eq!(path.stat().unwrap().size, 1000);
} | }
}
}
| random_line_split |
stat.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 dir = TempDir::new_in(&Path::new("."), "").unwrap();
let path = dir.path().join("file");
{
match File::create(&path) {
Err(..) => unreachable!(),
Ok(f) => {
let mut f = f;
for _ in range(0u, 1000) {
f.write(&[0]);
... | identifier_body | |
du.rs | (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate time;
#[macro_use]
extern crate uucore;
use std::fs;
use std::iter;
use std::io::{stderr, Result, Write};
use std::os::unix::f... | Ok(entry) => match Stat::new(entry.path()) {
Ok(this_stat) => {
if this_stat.is_dir {
futures.push(du(this_stat, options, depth + 1, inodes));
} else {
if inodes.contains(&this_sta... | let mut stats = vec![];
let mut futures = vec![];
if my_stat.is_dir {
let read = match fs::read_dir(&my_stat.path) {
Ok(read) => read,
Err(e) => {
safe_writeln!(
stderr(),
"{}: cannot read directory ‘{}‘: {}",
... | identifier_body |
du.rs | (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate time;
#[macro_use]
extern crate uucore;
use std::fs;
use std::iter;
use std::io::{stderr, Result, Write};
use std::os::unix::f... | mut my_stat: Stat,
options: &Options,
depth: usize,
inodes: &mut HashSet<u64>,
) -> Box<DoubleEndedIterator<Item = Stat>> {
let mut stats = vec![];
let mut futures = vec![];
if my_stat.is_dir {
let read = match fs::read_dir(&my_stat.path) {
Ok(read) => read,
Er... | identifier_name | |
du.rs | * (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate time;
#[macro_use]
extern crate uucore;
use std::fs;
use std::iter;
use std::io::{stderr, Result, Write};
use std::os::unix:... | }
impl Stat {
fn new(path: PathBuf) -> Result<Stat> {
let metadata = fs::symlink_metadata(&path)?;
Ok(Stat {
path: path,
is_dir: metadata.is_dir(),
size: metadata.len(),
blocks: metadata.blocks() as u64,
nlink: metadata.nlink() as u64,
... | created: u64,
accessed: u64,
modified: u64, | random_line_split |
du.rs | (c) Derek Chiang <derekchiang93@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate time;
#[macro_use]
extern crate uucore;
use std::fs;
use std::iter;
use std::io::{stderr, Result, Write};
use std::os::unix::f... | },
None => stat.modified,
};
((time / 1000) as i64, (time % 1000 * 1000000) as i32)
};
time::at(Timespec::new(secs, nsecs))
... | show_error!(
"invalid argument 'modified' for '--time'
Valid arguments are:
- 'accessed', 'created', 'modified'
Try '{} --help' for more information.",
NAME
... | conditional_block |
tri6.rs | use russell_lab::{Matrix, Vector};
/// Defines a triangle with 6 nodes (quadratic edges)
///
/// # Local IDs of nodes
///
/// ```text
/// s
/// |
/// 2, (0,1)
/// | ',
/// | ',
/// | ',
/// | ',
/// 5 4,
/// | ',
/// | ',
/// | ',
/// | (0,0) ', (1,0)
/... | /// 2| \
/// | \
/// |_____\
/// 0
/// ```
pub struct Tri6 {}
impl Tri6 {
pub const NDIM: usize = 2;
pub const NNODE: usize = 6;
pub const NEDGE: usize = 3;
pub const NFACE: usize = 0;
pub const EDGE_NNODE: usize = 3;
pub const FACE_NNODE: usize = 0;
pub const FACE_NEDGE: usize =... | /// | \ 1 | random_line_split |
tri6.rs | use russell_lab::{Matrix, Vector};
/// Defines a triangle with 6 nodes (quadratic edges)
///
/// # Local IDs of nodes
///
/// ```text
/// s
/// |
/// 2, (0,1)
/// | ',
/// | ',
/// | ',
/// | ',
/// 5 4,
/// | ',
/// | ',
/// | ',
/// | (0,0) ', (1,0)
/... | (interp: &mut Vector, ksi: &[f64]) {
let (r, s) = (ksi[0], ksi[1]);
interp[0] = 1.0 - (r + s) * (3.0 - 2.0 * (r + s));
interp[1] = r * (2.0 * r - 1.0);
interp[2] = s * (2.0 * s - 1.0);
interp[3] = 4.0 * r * (1.0 - (r + s));
interp[4] = 4.0 * r * s;
interp[5] = 4.... | calc_interp | identifier_name |
lexical-scope-in-unconditional-loop.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | fn sentinel() {()} |
fn zzz() {()} | random_line_split |
lexical-scope-in-unconditional-loop.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
zzz();
sentinel();
x += 1;
zzz();
sentinel();
// Shadow x
let x = x + 100;
zzz();
sentinel();
// open scope within loop's top level scope
{
zzz();
sentinel();
let x = -987i;
zzz... | {
break;
} | conditional_block |
lexical-scope-in-unconditional-loop.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {()}
| sentinel | identifier_name |
lexical-scope-in-unconditional-loop.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {()} | identifier_body | |
util.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 ... |
}
/// A writer which will move data into the void.
pub struct Sink { _priv: () }
/// Creates an instance of a writer which will successfully consume all data.
///
/// All calls to `write` on the returned instance will return `Ok(buf.len())`
/// and the contents of the buffer will not be inspected.
pub fn sink() -> S... | {
for slot in buf.iter_mut() {
*slot = self.byte;
}
Ok(buf.len())
} | identifier_body |
util.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 ... | { _priv: () }
/// Creates an instance of a writer which will successfully consume all data.
///
/// All calls to `write` on the returned instance will return `Ok(buf.len())`
/// and the contents of the buffer will not be inspected.
pub fn sink() -> Sink { Sink { _priv: () } }
impl Write for Sink {
fn write(&mut ... | Sink | identifier_name |
util.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 ... | }
assert_eq!(buf, [4, 4, 4, 4, 4, 0, 0, 0, 0, 0]);
}
#[test]
fn broadcast() {
let mut buf1 = [0; 10];
let mut buf2 = [0; 10];
{
let mut ptr1: &mut [u8] = &mut buf1;
let mut ptr2: &mut [u8] = &mut buf2;
assert_eq!((&mut ptr1).broad... | random_line_split | |
htmltablecolelement.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::HTMLTableColElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTa... | use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLTableColElement {
htmlelement: HTMLElement,
}
impl HTMLTableColElementDerived for EventTarget {
fn is_htmltablecolelement(&se... | use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId}; | random_line_split |
htmltablecolelement.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::HTMLTableColElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTa... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTableColElement> {
let element = HTMLTableColElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTableColElementBi... | {
HTMLTableColElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTableColElement, localName, prefix, document)
}
} | identifier_body |
htmltablecolelement.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::HTMLTableColElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTa... | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTableColElement> {
let element = HTMLTableColElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTableColElementBinding::Wrap)
}
}
| new | identifier_name |
sodium.rs | extern crate errno;
extern crate libc;
extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use self::libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, S... | }
} | random_line_split | |
sodium.rs | extern crate errno;
extern crate libc;
extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use self::libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, S... |
}
extern {
fn crypto_pwhash_alg_argon2i13() -> c_int;
fn crypto_pwhash_argon2i_opslimit_moderate() -> size_t;
fn crypto_pwhash_argon2i_memlimit_moderate() -> size_t;
fn crypto_pwhash_argon2i_opslimit_interactive() -> size_t;
fn crypto_pwhash_argon2i_memlimit_interactive() -> size_t;
fn crypto... | {
Err(IndyError::from_msg(IndyErrorKind::InvalidState, "Sodium pwhash failed"))
} | conditional_block |
sodium.rs | extern crate errno;
extern crate libc;
extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use self::libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, S... |
#[test]
fn salt_serialize_deserialize_works() {
let salt = gen_salt();
let serialized = rmp_serde::to_vec(&salt).unwrap();
let deserialized: Salt = rmp_serde::from_slice(&serialized).unwrap();
assert_eq!(serialized.len(), SALTBYTES + 2);
assert_eq!(salt, deserialized)
... | {
let salt = gen_salt();
assert_eq!(salt[..].len(), SALTBYTES)
} | identifier_body |
sodium.rs | extern crate errno;
extern crate libc;
extern crate serde;
extern crate sodiumoxide;
use domain::wallet::KeyDerivationMethod;
use errors::prelude::*;
use self::libc::{c_int, c_ulonglong, size_t};
use self::sodiumoxide::crypto::pwhash;
pub const SALTBYTES: usize = pwhash::SALTBYTES;
sodium_type!(Salt, pwhash::Salt, S... | () {
let salt = gen_salt();
let serialized = rmp_serde::to_vec(&salt).unwrap();
let deserialized: Salt = rmp_serde::from_slice(&serialized).unwrap();
assert_eq!(serialized.len(), SALTBYTES + 2);
assert_eq!(salt, deserialized)
}
#[test]
fn pwhash_works() {
le... | salt_serialize_deserialize_works | identifier_name |
cell.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/. */
//! A shareable mutable container for the DOM.
use dom::bindings::trace::JSTraceable;
use js::jsapi::{JSTracer};
... | /// # Panics
///
/// Panics if this is called off the script thread.
pub fn try_borrow(&self) -> Option<Ref<T>> {
debug_assert!(task_state::get().is_script());
match self.value.borrow_state() {
BorrowState::Writing => None,
_ => Some(self.value.borrow()),
... | ///
/// Returns `None` if the value is currently mutably borrowed.
/// | random_line_split |
cell.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/. */
//! A shareable mutable container for the DOM.
use dom::bindings::trace::JSTraceable;
use js::jsapi::{JSTracer};
... | <T> {
value: RefCell<T>,
}
// Functionality specific to Servo's `DOMRefCell` type
// ===================================================
impl<T> DOMRefCell<T> {
/// Return a reference to the contents.
///
/// For use in the layout task only.
#[allow(unsafe_code)]
pub unsafe fn borrow_for_layou... | DOMRefCell | identifier_name |
cell.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/. */
//! A shareable mutable container for the DOM.
use dom::bindings::trace::JSTraceable;
use js::jsapi::{JSTracer};
... |
}
impl<T: JSTraceable> JSTraceable for DOMRefCell<T> {
fn trace(&self, trc: *mut JSTracer) {
unsafe {
(*self).borrow_for_gc_trace().trace(trc)
}
}
}
// Functionality duplicated with `core::cell::RefCell`
// ===================================================
impl<T> DOMRefCell<T> ... | {
debug_assert!(task_state::get().is_script());
match self.value.borrow_state() {
BorrowState::Unused => Some(self.value.borrow_mut()),
_ => None,
}
} | identifier_body |
support.rs | #![no_std]
#![allow(visible_private_types)]
#![allow(non_camel_case_types)]
extern "rust-intrinsic" {
fn offset<T>(dst: *mut T, offset: int) -> *mut T;
}
extern "rust-intrinsic" {
fn offset<T>(dst: *const T, offset: int) -> *const T;
}
type c_int = i32;
#[no_mangle]
pub extern "C" fn memcpy(dest: *mut u8, s... | }
} | } | random_line_split |
support.rs | #![no_std]
#![allow(visible_private_types)]
#![allow(non_camel_case_types)]
extern "rust-intrinsic" {
fn offset<T>(dst: *mut T, offset: int) -> *mut T;
}
extern "rust-intrinsic" {
fn offset<T>(dst: *const T, offset: int) -> *const T;
}
type c_int = i32;
#[no_mangle]
pub extern "C" fn memcpy(dest: *mut u8, s... | {
unsafe {
let mut i = 0;
while i < n {
*(offset(s, i) as *mut u8) = c as u8;
i += 1;
}
}
} | identifier_body | |
support.rs | #![no_std]
#![allow(visible_private_types)]
#![allow(non_camel_case_types)]
extern "rust-intrinsic" {
fn offset<T>(dst: *mut T, offset: int) -> *mut T;
}
extern "rust-intrinsic" {
fn offset<T>(dst: *const T, offset: int) -> *const T;
}
type c_int = i32;
#[no_mangle]
pub extern "C" fn | (dest: *mut u8, src: *const u8, n: int) {
unsafe {
let mut i = 0;
while i < n {
*(offset(dest, i) as *mut u8) = *(offset(src, i));
i += 1;
}
}
}
#[no_mangle]
pub extern "C" fn memmove(dest: *mut u8, src: *const u8, n: int) {
unsafe {
if src < dest as ... | memcpy | identifier_name |
support.rs | #![no_std]
#![allow(visible_private_types)]
#![allow(non_camel_case_types)]
extern "rust-intrinsic" {
fn offset<T>(dst: *mut T, offset: int) -> *mut T;
}
extern "rust-intrinsic" {
fn offset<T>(dst: *const T, offset: int) -> *const T;
}
type c_int = i32;
#[no_mangle]
pub extern "C" fn memcpy(dest: *mut u8, s... | else { // copy from beginning
let mut i = 0;
while i < n {
*(offset(dest, i) as *mut u8) = *(offset(src, i));
i += 1;
}
}
}
}
#[no_mangle]
pub extern "C" fn memset(s: *mut u8, c: c_int, n: int) {
unsafe {
let mut i = 0;
... | { // copy from end
let mut i = n;
while i != 0 {
i -= 1;
*(offset(dest, i) as *mut u8) = *(offset(src, i));
}
} | conditional_block |
main.rs | extern crate bf;
extern crate clap;
use std::io::prelude::*;
use std::io::stdout;
use std::fs::File;
use bf::*;
use clap::{Arg, App};
fn main() {
let matches = App::new("bfi")
.version("0.1.0")
.author("David Barentt <david@barnett.net.nz>")
.about("A... |
};
if let Err(e) = file.read_to_string(&mut s) {
println!("Error while reading from `{}`: {}", f, e);
return;
}
s
} else {
println!("{}", matches.usage());
return;
}
};
match BFProgram::pars... | {
println!("Error while opening file `{}`: {}", f, e);
return;
} | conditional_block |
main.rs | extern crate bf;
extern crate clap;
use std::io::prelude::*;
use std::io::stdout;
use std::fs::File;
use bf::*;
use clap::{Arg, App};
fn main() {
let matches = App::new("bfi")
.version("0.1.0")
.author("David Barentt <david@barnett.net.nz>")
.about("A... | } | } | random_line_split |
main.rs | extern crate bf;
extern crate clap;
use std::io::prelude::*;
use std::io::stdout;
use std::fs::File;
use bf::*;
use clap::{Arg, App};
fn main() | } else {
if let Some(f) = matches.value_of("FILE") {
let mut s = String::new();
let mut file = match File::open(f) {
Ok(fi) => fi,
Err(e) => {
println!("Error while opening file `{}`: {}", f, e);
return;
... | {
let matches = App::new("bfi")
.version("0.1.0")
.author("David Barentt <david@barnett.net.nz>")
.about("A rust implementation of brainfuck")
.arg(Arg::with_name("CODE").help("brainfuck code to execute"))
... | identifier_body |
main.rs | extern crate bf;
extern crate clap;
use std::io::prelude::*;
use std::io::stdout;
use std::fs::File;
use bf::*;
use clap::{Arg, App};
fn | () {
let matches = App::new("bfi")
.version("0.1.0")
.author("David Barentt <david@barnett.net.nz>")
.about("A rust implementation of brainfuck")
.arg(Arg::with_name("CODE").help("brainfuck code to execute"))
.a... | main | identifier_name |
gc-vec.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 ... | () {
// A fixed-size array allocated in a garbage-collected box
let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(x[0], 1);
assert_eq!(x[6], 7);
assert_eq!(x[9], 10);
let y = x;
assert!(*y == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}
| main | identifier_name |
gc-vec.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 ... | {
// A fixed-size array allocated in a garbage-collected box
let x = box(GC) [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert_eq!(x[0], 1);
assert_eq!(x[6], 7);
assert_eq!(x[9], 10);
let y = x;
assert!(*y == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
} | identifier_body | |
gc-vec.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 y = x;
assert!(*y == [1i, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
} | assert_eq!(x[6], 7);
assert_eq!(x[9], 10);
| random_line_split |
to_url.rs | use url::{mod, Url, UrlParser};
pub trait ToUrl {
fn to_url(self) -> Result<Url, String>;
}
impl ToUrl for Url {
fn to_url(self) -> Result<Url, String> {
Ok(self)
}
}
impl<'a> ToUrl for &'a Url {
fn to_url(self) -> Result<Url, String> {
Ok(self.clone())
}
}
impl<'a> ToUrl for &'a... | {
match s {
"git" => url::RelativeScheme(9418),
"ssh" => url::RelativeScheme(22),
s => url::whatwg_scheme_type_mapper(s),
}
} | identifier_body | |
to_url.rs | use url::{mod, Url, UrlParser};
pub trait ToUrl {
fn to_url(self) -> Result<Url, String>;
}
impl ToUrl for Url {
fn to_url(self) -> Result<Url, String> {
Ok(self)
}
}
impl<'a> ToUrl for &'a Url {
fn to_url(self) -> Result<Url, String> {
Ok(self.clone())
}
}
| }
}
impl<'a> ToUrl for &'a Path {
fn to_url(self) -> Result<Url, String> {
Url::from_file_path(self).map_err(|()| {
format!("invalid path url `{}`", self.display())
})
}
}
fn mapper(s: &str) -> url::SchemeType {
match s {
"git" => url::RelativeScheme(9418),
... | impl<'a> ToUrl for &'a str {
fn to_url(self) -> Result<Url, String> {
UrlParser::new().scheme_type_mapper(mapper).parse(self).map_err(|s| {
format!("invalid url `{}`: {}", self, s)
}) | random_line_split |
to_url.rs | use url::{mod, Url, UrlParser};
pub trait ToUrl {
fn to_url(self) -> Result<Url, String>;
}
impl ToUrl for Url {
fn to_url(self) -> Result<Url, String> {
Ok(self)
}
}
impl<'a> ToUrl for &'a Url {
fn to_url(self) -> Result<Url, String> {
Ok(self.clone())
}
}
impl<'a> ToUrl for &'a... | (self) -> Result<Url, String> {
Url::from_file_path(self).map_err(|()| {
format!("invalid path url `{}`", self.display())
})
}
}
fn mapper(s: &str) -> url::SchemeType {
match s {
"git" => url::RelativeScheme(9418),
"ssh" => url::RelativeScheme(22),
s => url::... | to_url | identifier_name |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... |
% endif
</%helpers:longhand>
${helpers.single_keyword("text-decoration-style",
"-moz-none solid double dotted dashed wavy",
products="gecko")}
${helpers.predefined_type(
"text-decoration-color", "CSSColor",
"CSSParserColor::RGBA(RGBA { red: 0.0, green: 0.... | {
longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context);
} | identifier_body |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... | {
pub underline: bool,
pub overline: bool,
pub line_through: bool,
// 'blink' is accepted in the parser but ignored.
// Just not blinking the text is a conforming implementation per CSS 2.1.
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> ... | SpecifiedValue | identifier_name |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... |
try!(dest.write_str("line-through"));
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(non_upper_case_globals)]
pub const none: T = super::SpecifiedValue {
underline: false, overline: false, lin... | {
try!(dest.write_str(" "));
} | conditional_block |
text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Tex... | }
% if product == "servo":
fn cascade_property_custom<C: ComputedValues>(
_declaration: &PropertyDeclaration,
_inherited_style: &C,
context: &mut computed::Context<C>,
... | }
}
if !empty { Ok(result) } else { Err(()) } | random_line_split |
eq.rs | use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen;
use malachi... | else {
println!("{} ≠ {}", xs, ys);
}
}
}
#[allow(clippy::no_effect, unused_must_use)]
fn benchmark_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark(
"RationalSequence == RationalSequence",
BenchmarkType::Single,
un... | {
println!("{} = {}", xs, ys);
} | conditional_block |
eq.rs | use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen;
use malachi... | (gm: GenMode, config: GenConfig, limit: usize) {
for (xs, ys) in unsigned_rational_sequence_pair_gen::<u8>()
.get(gm, &config)
.take(limit)
{
if xs == ys {
println!("{} = {}", xs, ys);
} else {
println!("{} ≠ {}", xs, ys);
}
}
}
#[allow(clippy::... | demo_rational_sequence_eq | identifier_name |
eq.rs | use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen;
use malachi... | if xs == ys {
println!("{} = {}", xs, ys);
} else {
println!("{} ≠ {}", xs, ys);
}
}
}
#[allow(clippy::no_effect, unused_must_use)]
fn benchmark_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark(
"Rational... | fn demo_rational_sequence_eq(gm: GenMode, config: GenConfig, limit: usize) {
for (xs, ys) in unsigned_rational_sequence_pair_gen::<u8>()
.get(gm, &config)
.take(limit)
{ | random_line_split |
eq.rs | use malachite_base_test_util::bench::bucketers::pair_rational_sequence_max_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_rational_sequence_pair_gen;
use malachi... | run_benchmark(
"RationalSequence == RationalSequence",
BenchmarkType::Single,
unsigned_rational_sequence_pair_gen::<u8>().get(gm, &config),
gm.name(),
limit,
file_name,
&pair_rational_sequence_max_len_bucketer("xs", "ys"),
&mut [("Malachite", &mut |(xs... | identifier_body | |
main.rs | /// A genetic algorithm in Rust
/// Copyright (C) 2015 Andrew Schwartzmeyer
#[macro_use]
extern crate clap;
extern crate rand;
extern crate time;
use clap::{App, Arg};
use std::thread;
mod algorithm;
mod individual;
mod problem;
arg_enum!{
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Problem {
... |
}
}
| {
println!("{} converged to {} after {} generations in {} seconds.",
results.problem, results.individual.fitness,
results.iterations, results.duration);
println!("{:?}", results.individual.solution);
} | conditional_block |
main.rs | /// A genetic algorithm in Rust
/// Copyright (C) 2015 Andrew Schwartzmeyer
#[macro_use]
extern crate clap; |
mod algorithm;
mod individual;
mod problem;
arg_enum!{
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Problem {
Ackley,
Griewangk,
Rastrigin,
Rosenbrock,
Schwefel,
Sphere
}
}
#[derive(Debug, Copy, Clone)]
pub struct Parameters {
tolerance: f64,
... | extern crate rand;
extern crate time;
use clap::{App, Arg};
use std::thread; | random_line_split |
main.rs | /// A genetic algorithm in Rust
/// Copyright (C) 2015 Andrew Schwartzmeyer
#[macro_use]
extern crate clap;
extern crate rand;
extern crate time;
use clap::{App, Arg};
use std::thread;
mod algorithm;
mod individual;
mod problem;
arg_enum!{
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Problem {
... | {
tolerance: f64,
dimension: usize,
population: usize,
iterations: usize,
selection: usize,
elitism: usize,
mutation: f64,
crossover: f64,
verbosity: usize
}
/// Setup and run algorithm to search for solution
fn main() {
let matches = App::new("rust-genetic-algorithm")
.... | Parameters | identifier_name |
bounds.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 ... | should be implemented explicitly",
*tname))
}
ref tname => {
cx.span_bug(span,
&format!("expected built-in trait name but \
... | return cx.span_err(span,
&format!("{} is an unsafe trait and it \ | random_line_split |
bounds.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>(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Item,
push: F) where
F: FnOnce(P<Item>),
{
let name = match mitem.node {
MetaWord(ref tname) => {
match &... | expand_deriving_bound | identifier_name |
bounds.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 ... | a trait")
}
};
let path = Path::new(vec![
if cx.use_std { "std" } else { "core" },
"marker",
name
]);
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path,
additional_bounds: Vec:... | {
let name = match mitem.node {
MetaWord(ref tname) => {
match &tname[..] {
"Copy" => "Copy",
"Send" | "Sync" => {
return cx.span_err(span,
&format!("{} is an unsafe trait and it \
... | identifier_body |
shootout-threadring.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 n_tasks = if args.len() > 2u {
FromStr::from_str(args[2]).get()
}
else {
503
};
start(n_tasks, token);
}
| {
1000
} | conditional_block |
shootout-threadring.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 ... |
fn main() {
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"2000000", ~"503"]
}
else {
os::args()
};
let token = if args.len() > 1u {
FromStr::from_str(args[1]).get()
}
else {
1000
};
let n_tasks = if args.len() > 2u {
FromStr::f... | {
while (true) {
match p.recv() {
1 => {
println(fmt!("%d\n", id));
return;
}
token => {
debug!("thread: %d got token: %d", id, token);
ch.send(token - 1);
if token <= n_tasks {
return;
}
... | identifier_body |
shootout-threadring.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 ... | return;
}
}
}
}
}
fn main() {
let args = if os::getenv(~"RUST_BENCH").is_some() {
~[~"", ~"2000000", ~"503"]
}
else {
os::args()
};
let token = if args.len() > 1u {
FromStr::from_str(args[1]).get()
}
else {
10... | ch.send(token - 1);
if token <= n_tasks { | random_line_split |
shootout-threadring.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 ... | (id: int, n_tasks: int, p: &Port<int>, ch: &Chan<int>) {
while (true) {
match p.recv() {
1 => {
println(fmt!("%d\n", id));
return;
}
token => {
debug!("thread: %d got token: %d", id, token);
ch.send(token - 1);
if to... | roundtrip | identifier_name |
event.rs | //! Interfaces to VST events.
// TODO: Update and explain both host and plugin events
use std::{mem, slice};
use api::flags::*;
use api::{self, flags};
/// A VST event.
pub enum Event<'a> {
/// A midi event.
///
/// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` ... | }
SysEx => Event::SysEx {
payload: unsafe {
// We can safely transmute the event pointer to a `SysExEvent` pointer as
// event_type refers to a `SysEx` type.
let event: &api::SysExEvent = mem::transmute(&event);
... | {
use api::EventType::*;
match event.event_type {
Midi => {
let event: api::MidiEvent = unsafe { mem::transmute(event) };
let length = if event.note_length > 0 { Some(event.note_length) } else { None };
let offset = if event.note_offset > 0 {... | identifier_body |
event.rs | //! Interfaces to VST events.
// TODO: Update and explain both host and plugin events
use std::{mem, slice};
use api::flags::*;
use api::{self, flags};
/// A VST event.
pub enum Event<'a> {
/// A midi event.
///
/// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` ... | ;
let flags = flags::MidiEvent::from_bits(event.flags).unwrap();
Event::Midi {
data: event.midi_data,
delta_frames: event.delta_frames,
live: flags.intersects(REALTIME_EVENT),
note_length: length,
... | { None } | conditional_block |
event.rs | //! Interfaces to VST events.
// TODO: Update and explain both host and plugin events
use std::{mem, slice};
use api::flags::*;
use api::{self, flags};
/// A VST event.
pub enum Event<'a> {
/// A midi event.
///
/// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` ... | /// Offset in samples into note from note start, if available.
note_offset: Option<i32>,
/// Detuning between -63 and +64 cents.
detune: i8,
/// Note off velocity between 0 and 127.
note_off_velocity: u8,
},
/// A system exclusive event.
///
/// This is... | /// The length of the midi note associated with this event, if available.
note_length: Option<i32>,
| random_line_split |
event.rs | //! Interfaces to VST events.
// TODO: Update and explain both host and plugin events
use std::{mem, slice};
use api::flags::*;
use api::{self, flags};
/// A VST event.
pub enum | <'a> {
/// A midi event.
///
/// These are sent to the plugin before `Plugin::processing()` or `Plugin::processing_f64()` is
/// called.
Midi {
/// The raw midi data associated with this event.
data: [u8; 3],
/// Number of samples into the current processing block that this ... | Event | identifier_name |
request_registration_token_via_msisdn.rs | //! `POST /_matrix/client/*/register/msisdn/requestToken`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3registermsisdnrequesttoken
use js_int::UInt;
use ruma_common::{api::ruma_api, ClientSecret, SessionId};
use crate::acco... |
}
impl Response {
/// Creates a new `Response` with the given session identifier.
pub fn new(sid: Box<SessionId>) -> Self {
Self { sid, submit_url: None }
}
}
}
| {
Self {
client_secret,
country,
phone_number,
send_attempt,
next_link: None,
identity_server_info: None,
}
} | identifier_body |
request_registration_token_via_msisdn.rs | //! `POST /_matrix/client/*/register/msisdn/requestToken`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3registermsisdnrequesttoken
use js_int::UInt;
use ruma_common::{api::ruma_api, ClientSecret, SessionId};
use crate::acco... | }
impl<'a> Request<'a> {
/// Creates a new `Request` with the given client secret, country code, phone number and
/// send-attempt counter.
pub fn new(
client_secret: &'a ClientSecret,
country: &'a str,
phone_number: &'a str,
send_attempt:... | random_line_split | |
request_registration_token_via_msisdn.rs | //! `POST /_matrix/client/*/register/msisdn/requestToken`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3registermsisdnrequesttoken
use js_int::UInt;
use ruma_common::{api::ruma_api, ClientSecret, SessionId};
use crate::acco... | (sid: Box<SessionId>) -> Self {
Self { sid, submit_url: None }
}
}
}
| new | identifier_name |
main.rs | #![feature(box_syntax)]
extern crate e2d2;
extern crate getopts;
extern crate rand;
extern crate time;
use e2d2::allocators::*;
use e2d2::common::*;
use e2d2::headers::*;
use e2d2::interface::*;
use e2d2::interface::dpdk::*;
use e2d2::operators::*;
use e2d2::scheduler::Executable;
use e2d2::state::*;
use getopts::Optio... |
fn recv_thread(ports: Vec<CacheAligned<PortQueue>>, core: i32, counter: MergeableStoreDP<isize>) {
init_thread(core, core);
println!("Receiving started");
let pipelines: Vec<_> = ports
.iter()
.map(|port| {
let ctr = counter.clone();
monitor(ReceiveBatch::new(port.cl... | {
parent
.parse::<MacHeader>()
.transform(box |pkt| {
let hdr = pkt.get_mut_header();
hdr.swap_addresses();
})
.parse::<IpHeader>()
.transform(box move |pkt| {
let hdr = pkt.get_mut_header();
let ttl = hdr.ttl();
hdr... | identifier_body |
main.rs | #![feature(box_syntax)]
extern crate e2d2;
extern crate getopts;
extern crate rand;
extern crate time;
use e2d2::allocators::*;
use e2d2::common::*;
use e2d2::headers::*;
use e2d2::interface::*;
use e2d2::interface::dpdk::*;
use e2d2::operators::*;
use e2d2::scheduler::Executable;
use e2d2::state::*;
use getopts::Optio... | else {
init_system_secondary(&name, master_core);
}
let ports_to_activate: Vec<_> = cores_for_port.keys().collect();
let mut queues_by_core = HashMap::<i32, Vec<_>>::with_capacity(cores.len());
let mut ports = Vec::<Arc<PmdPort>>::with_capacity(ports_to_activate.len());
for port in &ports... | {
init_system_wl(&name, master_core, &[]);
} | conditional_block |
main.rs | #![feature(box_syntax)]
extern crate e2d2;
extern crate getopts;
extern crate rand;
extern crate time;
use e2d2::allocators::*;
use e2d2::common::*;
use e2d2::headers::*;
use e2d2::interface::*;
use e2d2::interface::dpdk::*;
use e2d2::operators::*;
use e2d2::scheduler::Executable;
use e2d2::state::*;
use getopts::Optio... | } | random_line_split | |
main.rs | #![feature(box_syntax)]
extern crate e2d2;
extern crate getopts;
extern crate rand;
extern crate time;
use e2d2::allocators::*;
use e2d2::common::*;
use e2d2::headers::*;
use e2d2::interface::*;
use e2d2::interface::dpdk::*;
use e2d2::operators::*;
use e2d2::scheduler::Executable;
use e2d2::state::*;
use getopts::Optio... | (ports: &[String], cores: &[i32]) -> HashMap<String, Vec<i32>> {
let mut cores_for_port = HashMap::<String, Vec<i32>>::new();
for (port, core) in ports.iter().zip(cores.iter()) {
cores_for_port
.entry(port.clone())
.or_insert(vec![])
.push(*core)
... | extract_cores_for_port | identifier_name |
square.rs | use crate::Color;
use std::fmt;
use std::iter;
const ASCII_1: u8 = b'1';
const ASCII_9: u8 = b'9';
const ASCII_LOWER_A: u8 = b'a';
const ASCII_LOWER_I: u8 = b'i';
/// Represents a position of each cell in the game board.
///
/// # Examples
///
/// ```
/// use shogi::Square;
///
/// let sq = Square::new(4, 4).unwrap()... | /// Returns an iterator of all variants.
pub fn iter() -> SquareIter {
SquareIter { current: 0 }
}
/// Returns a file of the square.
pub fn file(self) -> u8 {
self.inner / 9
}
/// Returns a rank of the square.
pub fn rank(self) -> u8 {
self.inner % 9
}
... | }
Some(Square { inner: index })
}
| random_line_split |
square.rs | use crate::Color;
use std::fmt;
use std::iter;
const ASCII_1: u8 = b'1';
const ASCII_9: u8 = b'9';
const ASCII_LOWER_A: u8 = b'a';
const ASCII_LOWER_I: u8 = b'i';
/// Represents a position of each cell in the game board.
///
/// # Examples
///
/// ```
/// use shogi::Square;
///
/// let sq = Square::new(4, 4).unwrap()... |
Some(Square { inner: index })
}
/// Returns an iterator of all variants.
pub fn iter() -> SquareIter {
SquareIter { current: 0 }
}
/// Returns a file of the square.
pub fn file(self) -> u8 {
self.inner / 9
}
/// Returns a rank of the square.
pub fn rank(s... | {
return None;
} | conditional_block |
square.rs | use crate::Color;
use std::fmt;
use std::iter;
const ASCII_1: u8 = b'1';
const ASCII_9: u8 = b'9';
const ASCII_LOWER_A: u8 = b'a';
const ASCII_LOWER_I: u8 = b'i';
/// Represents a position of each cell in the game board.
///
/// # Examples
///
/// ```
/// use shogi::Square;
///
/// let sq = Square::new(4, 4).unwrap()... |
#[test]
fn from_sfen() {
let ok_cases = [
("9a", 8, 0),
("1a", 0, 0),
("5e", 4, 4),
("9i", 8, 8),
("1i", 0, 8),
];
let ng_cases = ["", "9j", "_a", "a9", "9 ", " a", "9", "foo"];
for case in ok_cases.iter() {
... | {
for file in 0..9 {
for rank in 0..9 {
let sq = Square::new(file, rank).unwrap();
assert_eq!(file, sq.file());
assert_eq!(rank, sq.rank());
}
}
assert_eq!(None, Square::new(10, 0));
assert_eq!(None, Square::new(0, ... | identifier_body |
square.rs | use crate::Color;
use std::fmt;
use std::iter;
const ASCII_1: u8 = b'1';
const ASCII_9: u8 = b'9';
const ASCII_LOWER_A: u8 = b'a';
const ASCII_LOWER_I: u8 = b'i';
/// Represents a position of each cell in the game board.
///
/// # Examples
///
/// ```
/// use shogi::Square;
///
/// let sq = Square::new(4, 4).unwrap()... | () {
let cases = [
("9a", 8, 0),
("1a", 0, 0),
("5e", 4, 4),
("9i", 8, 8),
("1i", 0, 8),
];
for case in cases.iter() {
let sq = Square::new(case.1, case.2).unwrap();
assert_eq!(case.0, sq.to_string());
}... | to_sfen | identifier_name |
reference-to-struct.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn zzz() {()} | {
let stack_val: SomeStruct = SomeStruct { x: 10, y: 23.5 };
let stack_val_ref : &SomeStruct = &stack_val;
let stack_val_interior_ref_1 : &int = &stack_val.x;
let stack_val_interior_ref_2 : &f64 = &stack_val.y;
let ref_to_unnamed : &SomeStruct = &SomeStruct { x: 11, y: 24.5 };
let managed_val =... | identifier_body |
reference-to-struct.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 ... |
// GDB doesn't know about UTF-32 character encoding and will print a rust char as only its numerical
// value.
// compile-flags:-Z extra-debug-info
// debugger:break zzz
// debugger:run
// debugger:finish
// debugger:print *stack_val_ref
// check:$1 = {x = 10, y = 23.5}
// debugger:print *stack_val_interior_ref_1
/... |
// xfail-win32 Broken because of LLVM bug: http://llvm.org/bugs/show_bug.cgi?id=16249 | random_line_split |
reference-to-struct.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 ... | () {
let stack_val: SomeStruct = SomeStruct { x: 10, y: 23.5 };
let stack_val_ref : &SomeStruct = &stack_val;
let stack_val_interior_ref_1 : &int = &stack_val.x;
let stack_val_interior_ref_2 : &f64 = &stack_val.y;
let ref_to_unnamed : &SomeStruct = &SomeStruct { x: 11, y: 24.5 };
let managed_va... | main | identifier_name |
search.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::hash::Hash;
/// A node in a graph with a regular grid.
pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord {
/// List the neighbor nodes of this graph node.
fn neighbors(&self) -> Vec<Self>;
}
/// A pathfin... | let mut new_edge = HashSet::new();
for n in &edge {
for m in n.neighbors() {
if is_valid(&m) &&!weights.contains_key(&m) {
new_edge.insert(m);
}
}
}
edge = new_edge;
... | for n in &edge {
weights.insert(n.clone(), dist);
}
| random_line_split |
search.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::hash::Hash;
/// A node in a graph with a regular grid.
pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord {
/// List the neighbor nodes of this graph node.
fn neighbors(&self) -> Vec<Self>;
}
/// A pathfin... | else {
Some(path)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_astar() {
fn neighbors(origin: i32, &x: &i32) -> Vec<(i32, f32)> {
let mut ret = Vec::with_capacity(2);
for i in &[-1, 1] {
let x = x + i;
ret.push((x, (... | {
None
} | conditional_block |
search.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::hash::Hash;
/// A node in a graph with a regular grid.
pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord {
/// List the neighbor nodes of this graph node.
fn neighbors(&self) -> Vec<Self>;
}
/// A pathfin... | () {
fn neighbors(origin: i32, &x: &i32) -> Vec<(i32, f32)> {
let mut ret = Vec::with_capacity(2);
for i in &[-1, 1] {
let x = x + i;
ret.push((x, (x - origin).abs() as f32));
}
ret
}
assert_eq!(Some(vec![8]), astar... | test_astar | identifier_name |
search.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::hash::Hash;
/// A node in a graph with a regular grid.
pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord {
/// List the neighbor nodes of this graph node.
fn neighbors(&self) -> Vec<Self>;
}
/// A pathfin... | // Also flip the sign on the value, shorter distance means bigger value, since BinaryHeap
// returns the largest item first.
let value = ::std::u32::MAX - dist.to_bits();
MetricNode {
item,
value,
come_from,
}
}
let mut come_from = Has... | {
#[derive(Eq, PartialEq)]
struct MetricNode<N> {
value: u32,
item: N,
come_from: Option<N>,
}
impl<N: Eq> Ord for MetricNode<N> {
fn cmp(&self, other: &Self) -> Ordering { self.value.cmp(&other.value) }
}
impl<N: Eq> PartialOrd for MetricNode<N> {
fn part... | identifier_body |
try-macro.rs | // run-pass
#![allow(deprecated)] // for deprecated `try!()` macro
use std::num::{ParseFloatError, ParseIntError};
fn main() {
assert_eq!(simple(), Ok(1));
assert_eq!(nested(), Ok(2));
assert_eq!(merge_ok(), Ok(3.0));
assert_eq!(merge_int_err(), Err(Error::Int));
assert_eq!(merge_float_err(), Err(E... | (_: ParseFloatError) -> Error {
Error::Float
}
}
| from | identifier_name |
try-macro.rs | // run-pass
#![allow(deprecated)] // for deprecated `try!()` macro
use std::num::{ParseFloatError, ParseIntError};
fn main() {
assert_eq!(simple(), Ok(1));
assert_eq!(nested(), Ok(2));
assert_eq!(merge_ok(), Ok(3.0));
assert_eq!(merge_int_err(), Err(Error::Int));
assert_eq!(merge_float_err(), Err(E... |
#[derive(Debug, PartialEq)]
enum Error {
Int,
Float,
}
impl From<ParseIntError> for Error {
fn from(_: ParseIntError) -> Error {
Error::Int
}
}
impl From<ParseFloatError> for Error {
fn from(_: ParseFloatError) -> Error {
Error::Float
}
} | } | random_line_split |
try-macro.rs | // run-pass
#![allow(deprecated)] // for deprecated `try!()` macro
use std::num::{ParseFloatError, ParseIntError};
fn main() {
assert_eq!(simple(), Ok(1));
assert_eq!(nested(), Ok(2));
assert_eq!(merge_ok(), Ok(3.0));
assert_eq!(merge_int_err(), Err(Error::Int));
assert_eq!(merge_float_err(), Err(E... |
}
impl From<ParseFloatError> for Error {
fn from(_: ParseFloatError) -> Error {
Error::Float
}
}
| {
Error::Int
} | identifier_body |
linux.rs | // Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.com>
//
// 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... | // man 7 packet
pub struct packet_mreq {
pub mr_ifindex: libc::c_int,
pub mr_type: libc::c_ushort,
pub mr_alen: libc::c_ushort,
pub mr_address: [libc::c_uchar; 8]
} | pub const PACKET_MR_PROMISC: libc::c_int = 1;
| random_line_split |
linux.rs | // Copyright (c) 2014 Robert Clipsham <robert@octarineparrot.com>
//
// 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... | {
pub mr_ifindex: libc::c_int,
pub mr_type: libc::c_ushort,
pub mr_alen: libc::c_ushort,
pub mr_address: [libc::c_uchar; 8]
}
| packet_mreq | identifier_name |
constraint_conversion.rs | use rustc_infer::infer::canonical::QueryOutlivesConstraint;
use rustc_infer::infer::canonical::QueryRegionConstraints;
use rustc_infer::infer::outlives::env::RegionBoundPairs;
use rustc_infer::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelegate};
use rustc_infer::infer::region_constraints::{GenericKind, V... | TypeTest { generic_kind, lower_bound, locations: self.locations, verify_bound }
}
fn to_region_vid(&mut self, r: ty::Region<'tcx>) -> ty::RegionVid {
if let ty::RePlaceholder(placeholder) = r {
self.constraints.placeholder_region(self.infcx, *placeholder).to_region_vid()
} e... | region: ty::Region<'tcx>,
verify_bound: VerifyBound<'tcx>,
) -> TypeTest<'tcx> {
let lower_bound = self.to_region_vid(region);
| random_line_split |
constraint_conversion.rs | use rustc_infer::infer::canonical::QueryOutlivesConstraint;
use rustc_infer::infer::canonical::QueryRegionConstraints;
use rustc_infer::infer::outlives::env::RegionBoundPairs;
use rustc_infer::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelegate};
use rustc_infer::infer::region_constraints::{GenericKind, V... | <'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
tcx: TyCtxt<'tcx>,
universal_regions: &'a UniversalRegions<'tcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: Option<ty::Region<'tcx>>,
param_env: ty::ParamEnv<'tcx>,
locations: Locations,
category: ConstraintCategor... | ConstraintConversion | identifier_name |
main.rs | // Unseemly is a "core" typed language with (typed!) macros.
// You shouldn't write code in Unseemly.
// Instead, you should implement your programming language as Unseemly macros.
#![allow(dead_code, unused_macros, non_snake_case, non_upper_case_globals, deprecated)]
// dead_code and unused_macros are hopefully tempo... | (path: &std::path::Path) -> Language {
let mut raw_lib = String::new();
use std::io::Read;
let orig_dir = std::env::current_dir().unwrap();
std::fs::File::open(path)
.expect("Error opening file")
.read_to_string(&mut raw_lib)
.expect("Error reading file");
// Evaluate the file ... | language_from_file | identifier_name |
main.rs | // Unseemly is a "core" typed language with (typed!) macros.
// You shouldn't write code in Unseemly.
// Instead, you should implement your programming language as Unseemly macros.
#![allow(dead_code, unused_macros, non_snake_case, non_upper_case_globals, deprecated)]
// dead_code and unused_macros are hopefully tempo... |
/// Evaluate a program written in Unseemly.
/// Of course, it may immediately do `include /[something]/` to switch languages.
pub fn eval_unseemly_program_top(program: &str) -> Result<Value, String> {
eval_program(program, unseemly())
}
/// Type program written in Unseemly.
/// Of course, it may immediately do `... | {
// TODO: looks like `outermost_form` ought to be a property of `ParseContext`
let ast: Ast = crate::grammar::parse(&core_forms::outermost_form(), lang.pc, program)
.map_err(|e| e.msg)?;
let _type = ast_walk::walk::<ty::SynthTy>(
&ast,
&ast_walk::LazyWalkReses::new(lang.type_env, l... | identifier_body |
main.rs | // Unseemly is a "core" typed language with (typed!) macros.
// You shouldn't write code in Unseemly.
// Instead, you should implement your programming language as Unseemly macros.
#![allow(dead_code, unused_macros, non_snake_case, non_upper_case_globals, deprecated)]
// dead_code and unused_macros are hopefully tempo... | )
.map_err(|e| format!("{}", e))?;
let core_ast = crate::expand::expand(&ast).map_err(|_| "???".to_string())?;
eval(&core_ast, lang.value_env).map_err(|_| "???".to_string())
}
/// Evaluate a program written in Unseemly.
/// Of course, it may immediately do `include /[something]/` to switch languages.
... | .map_err(|e| e.msg)?;
let _type = ast_walk::walk::<ty::SynthTy>(
&ast,
&ast_walk::LazyWalkReses::new(lang.type_env, lang.type_env__phaseless, ast.clone()), | random_line_split |
lock_table.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(test)]
#![feature(bench_black_box)]
use concurrency_manager::ConcurrencyManager;
use criterion::*;
use futures::executor::block_on;
use rand::prelude::*;
use std::{borrow::Cow, hint::black_box, mem::forget};
use txn_types::{Key, Lock, LockT... | () -> ConcurrencyManager {
let cm = ConcurrencyManager::new(1.into());
let mut buf = [0; KEY_LEN];
for _ in 0..LOCK_COUNT {
thread_rng().fill_bytes(&mut buf[..]);
let key = Key::from_raw(&buf);
// Really rare to generate duplicate key. Do not consider it for simplicity.
let g... | prepare_cm | identifier_name |
lock_table.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(test)]
#![feature(bench_black_box)]
use concurrency_manager::ConcurrencyManager;
use criterion::*;
use futures::executor::block_on;
use rand::prelude::*;
use std::{borrow::Cow, hint::black_box, mem::forget};
use txn_types::{Key, Lock, LockT... |
criterion_group!(
benches,
point_check_baseline,
bench_point_check,
range_check_baseline,
bench_range_check
);
criterion_main!(benches); | })
});
} | random_line_split |
lock_table.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(test)]
#![feature(bench_black_box)]
use concurrency_manager::ConcurrencyManager;
use criterion::*;
use futures::executor::block_on;
use rand::prelude::*;
use std::{borrow::Cow, hint::black_box, mem::forget};
use txn_types::{Key, Lock, LockT... |
fn bench_range_check(c: &mut Criterion) {
let cm = prepare_cm();
let ts_set = TsSet::Empty;
c.bench_function("range_check_1k_in_10k_locks", |b| {
b.iter(|| {
let start = thread_rng().gen_range(0u8..230);
let start_key = Key::from_raw(&[start]);
let end_key = Key... | {
c.bench_function("range_check_baseline", |b| {
b.iter(|| {
let start = thread_rng().gen_range(0u8..245);
black_box(Key::from_raw(&[start]));
black_box(Key::from_raw(&[start + 25]));
})
});
} | identifier_body |
box.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/. */
//! Generic types for box properties.
use crate::values::animated::ToAnimatedZero;
/// A generic value for the ... |
}
/// https://drafts.csswg.org/css-animations/#animation-iteration-count
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToComputedValue, ToCss)]
pub enum AnimationIterationCount<Number> {
/// A `<number>` value.
Number(Number),
/// The `infinite` keyword.
Infinite,
}
/// A generi... | {
Err(())
} | identifier_body |
box.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/. */
//! Generic types for box properties.
use crate::values::animated::ToAnimatedZero;
/// A generic value for the ... | Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
)]
pub enum VerticalAlign<LengthOrPercentage> {
/// `baseline`
Baseline,
/// `sub`
Sub,
/// `super`
Super,
/// `top`
Top,
/// `text-top`
TextTop,
/// `middle`
Mid... | #[derive(
Animate,
Clone,
ComputeSquaredDistance, | random_line_split |
box.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/. */
//! Generic types for box properties.
use crate::values::animated::ToAnimatedZero;
/// A generic value for the ... | <Number> {
/// A `<number>` value.
Number(Number),
/// The `infinite` keyword.
Infinite,
}
/// A generic value for the `perspective` property.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,... | AnimationIterationCount | identifier_name |
narrowphase_behaviour.rs | macro_rules! assert_narrowphase_behaviour {
( $( $lines:item )+ ) => {
$( $lines )+
mod narrowphase_behaviour {
use std::mem;
use std::marker::PhantomData;
use super::type_marker;
use collisions::{BodyData, BodyDef, Narrowphase};
use col... | }
};
} | random_line_split | |
checkbox.rs | use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Printer;
use crate::Vec2;
use crate::With;
use std::rc::Rc;
/// Checkable box.
///
/// # Examples
///
/// ```
/// use cursive_core::... |
/// Sets a callback to be used when the state changes.
pub fn set_on_change<F:'static + Fn(&mut Cursive, bool)>(
&mut self,
on_change: F,
) {
self.on_change = Some(Rc::new(on_change));
}
/// Sets a callback to be used when the state changes.
///
/// Chainable varia... | {
Checkbox {
checked: false,
enabled: true,
on_change: None,
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.