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 |
|---|---|---|---|---|
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::... | if e.flags & libc::EV_EOF!= 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags!= 0 {
... | event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
| conditional_block |
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::... | ap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn c... | th_capacity(c | identifier_name |
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::... | ::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data!= 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
... | kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr... | random_line_split |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | pub use self::window::Window;
pub use sdl2::rect::{Point, Rect};
pub const FRAME_DELAY_MILLIS: u32 = 40;
// ========================================================================= // | pub use self::event::{Event, KeyMod, Keycode};
pub use self::font::Font;
pub use self::resources::Resources;
pub use self::sound::Sound;
pub use self::sprite::Sprite; | random_line_split |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone(); |
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8... | let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2); | random_line_split |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else |
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mu... | conditional_block |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone(... | (a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| xor | identifier_name |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone(... | {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
} | identifier_body | |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
}
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Floa... | {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
... | identifier_body |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
... | }
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => { | random_line_split |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ... | struct_ty | identifier_name |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... | else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extrac... | {
OutputMode::SortAndPrint
} | conditional_block |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... |
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the ... | {
unimplemented!()
} | identifier_body |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... | let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
... | // We need to make the strings owned to construct the `Options` instance. | random_line_split |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... | () {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg... | sort_array | identifier_name |
regions-trait-1.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 ... | <'a> { c: &'a ctxt }
impl<'a> get_ctxt for has_ctxt<'a> {
// Here an error occurs because we used `&self` but
// the definition used `&`:
fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
}
}
fn get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v... | has_ctxt | identifier_name |
regions-trait-1.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 get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v
}
fn main() {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
assert_eq!(get_v(box hc as Box<get_ctxt>), 22u);
} | fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
} | random_line_split |
filesearch.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... | FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
... | rslt = FileMatches;
} | random_line_split |
filesearch.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... | }
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if!found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
... | {
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
... | identifier_body |
filesearch.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... | <F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
... | search | identifier_name |
mod.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... | pub use reader::*;
mod validation;
pub use validation::*;
mod writer;
pub use writer::*;
#[cfg(feature = "insecure")]
#[cfg_attr(docsrs, doc(cfg(feature = "insecure")))]
pub mod insecure; | mod manager;
pub use manager::*;
mod mem_io;
pub use mem_io::*;
mod reader; | random_line_split |
os.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 ... |
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe... | random_line_split | |
os.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 ... | {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run... | identifier_body | |
os.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 msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, F... | {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
} | conditional_block |
os.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 ... | () -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
... | errno | identifier_name |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&se | f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
... | lf, | identifier_name |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter... | // le trait fmt::Display.
println!("{:?}", *color)
}
} | Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté | random_line_split |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter... | let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.ab... | ;
| conditional_block |
gtest_attribute.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
/// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked
/// into a C++ binary that invokes Gtest.
///
/// The `gtest` macro takes two arguments, which are Rust identifiers. ... | let test_fn = &input_fn.sig.ident;
// Implements ToTokens to generate a reference to a static-lifetime, null-terminated, C-String
// literal. It is represented as an array of type std::os::raw::c_char which can be either
// signed or unsigned depending on the platform, and it can be passed directly to ... | format_ident!("{}_{}_{}_{}", file_name, test_suite_name, test_name, f.sig.ident)
};
let run_test_fn = format_ident!("run_test_{}", mangled_function_name(&input_fn));
// The identifier of the function which contains the body of the test. | random_line_split |
gtest_attribute.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
/// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked
/// into a C++ binary that invokes Gtest.
///
/// The `gtest` macro takes two arguments, which are Rust identifiers. ... | {
TestSuite,
TestName,
}
// Returns a string representation of an identifier argument to the attribute. For example, for
// #[gtest(Foo, Bar)], this function would return "Foo" for position 0 and "Bar" for position 1.
// If the argument is not a Rust identifier or not present, it return... | GtestAttributeArgument | identifier_name |
gtest_attribute.rs | use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned;
/// The `gtest` macro can be placed on a function to make it into a Gtest unit test, when linked
/// into a C++ binary that invokes Gtest.
///
/// The `gtest` macro takes two arguments, which are Rust identifiers. ... | }
}
}
let args = syn::parse_macro_input!(arg_stream as syn::AttributeArgs);
let input_fn = syn::parse_macro_input!(input as syn::ItemFn);
if let Some(asyncness) = input_fn.sig.asyncness {
// TODO(crbug.com/1288947): We can support async functions once we have block_on() su... | {
let error_stream = match which {
GtestAttributeArgument::TestSuite => {
quote_spanned! {
args[pos].span() =>
compile_error!(
"Expected a test suite name, written as a... | conditional_block |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
... | }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
} | } | random_line_split |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn | (grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
... | min_path_sum | identifier_name |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 | arr[n - 1]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_path_sum() {
let grid = vec![vec![1, 3, 1], vec![1, 5, 1], vec![4, 2, 1]];
assert_eq!(Solution::min_path_sum(grid), 7);
}
}
| {
if grid.is_empty() {
return 0;
}
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
... | identifier_body |
no_0064_minimum_path_sum.rs | struct Solution;
impl Solution {
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
if grid.is_empty() |
let (m, n) = (grid.len(), grid[0].len());
let mut arr = vec![std::i32::MAX; n];
arr[0] = 0;
for i in 0..m {
for j in 0..n {
// 选择上面(arr[j])和左面(arr[j-1])最小的那个
if j == 0 {
// 左边没有,只有上面的元素
arr[j] = arr[j] +... | {
return 0;
} | conditional_block |
issue-59494.rs | fn | <A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
move |a: A| -> C { f(g(a)) }
}
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ga)
... | t7p | identifier_name |
issue-59494.rs | fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C |
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ga)
}
}
fn main() {
let f = |(_, _)| {};
let g = |(a, _)| a;
let t7 = |env| |a| |b| t7p(f, g)(... | {
move |a: A| -> C { f(g(a)) }
} | identifier_body |
issue-59494.rs | fn t7p<A, B, C>(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C {
move |a: A| -> C { f(g(a)) }
}
fn t8n<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C)
where
A: Copy,
{
move |a: A| -> (B, C) {
let b = a;
let fa = f(a);
let ga = g(b);
(fa, ... | let g = |(a, _)| a;
let t7 = |env| |a| |b| t7p(f, g)(((env, a), b));
let t8 = t8n(t7, t7p(f, g));
//~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)>
} | let f = |(_, _)| {}; | random_line_split |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | let mut x = BinarySearchTree::new();
x.insert(5);
x.insert(6);
assert!(x.contains(&5));
assert!(x.contains(&6));
assert!(!x.contains(&7));
}
#[test]
fn test_structure() {
let mut x = BinarySearchTree::new();
x.insert(10);
x.insert(15);... | fn test_insert_contains() { | random_line_split |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | <T> {
v: T,
left: NodePtr<T>,
right: NodePtr<T>,
}
type NodePtr<T> = Option<Box<Node<T>>>;
#[derive(Debug)]
pub struct BinarySearchTree<T> {
root: NodePtr<T>,
}
impl<T> Node<T> {
fn new(v: T) -> NodePtr<T> {
Some(Box::new(Self {
v,
left: None,
right: No... | Node | identifier_name |
bst.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
pub fn insert(&mut self, v: T)
where
T: Ord,
{
let slot = self.find_slot(&v);
if slot.is_none() {
*slot = Node::new(v);
}
}
pub fn contains(&self, v: &T) -> bool
where
T: Ord + std::fmt::Debug,
{
let mut current = &self.root;
... | {
let mut current = &mut self.root;
while current.is_some() {
if ¤t.as_ref().unwrap().v == v {
break;
}
use std::cmp::Ordering;
let inner = current.as_mut().unwrap();
match v.cmp(&inner.v) {
Ordering::Less ... | identifier_body |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io};
use log::Record;
use crate::stratis::{StratisErro... |
/// Notify systemd that a daemon has started.
#[allow(clippy::implicit_hasher)]
pub fn notify(unset_variable: bool, key_value_pairs: HashMap<String, String>) -> StratisResult<()> {
let serialized_pairs = serialize_pairs(key_value_pairs);
let cstring = CString::new(serialized_pairs)?;
let ret = unsafe { bi... | {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();
string += "\n";
string
})
} | identifier_body |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io}; | use log::Record;
use crate::stratis::{StratisError, StratisResult};
fn serialize_pairs(pairs: HashMap<String, String>) -> String {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();... | random_line_split | |
mod.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
mod bindings;
use std::{collections::HashMap, ffi::CString, io};
use log::Record;
use crate::stratis::{StratisErro... | (pairs: HashMap<String, String>) -> String {
pairs
.iter()
.map(|(key, value)| format!("{}={}", key, value))
.fold(String::new(), |mut string, key_value_pair| {
string += key_value_pair.as_str();
string += "\n";
string
})
}
/// Notify systemd that a ... | serialize_pairs | identifier_name |
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
... | {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<I... | NewLayoutThreadInfo | identifier_name |
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
... | use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use script_traits::Painter;
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;
use servo_channel::{Receiver, Sender};
use servo_url::ServoUrl;
use std::sync::Arc;
use style::context::QuirksMode;
use style::properties::PropertyId;
use style::sel... | random_line_split | |
message.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 {OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use euclid::{Point2D, Rect};
... |
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComp... | {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::NodesFromPointQuery(..) |
&QueryMsg::TextIndexQuery(..) |
&QueryMsg::ElementInnerTextQuery(_) => ... | identifier_body |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | format!("unknown pin function `{}`, allowed functions: {}",
fun, avaliable.join(", ")).as_str());
return;
},
Some(func_idx) => {
format!("AltFunction{}", func_idx)
}
}
}
}
}
};
let fu... | match maybe_func {
None => {
let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect();
cx.parse_sess().span_diagnostic.span_err(
node.get_attr("function").value_span, | random_line_split |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | (builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
for port_node in node.subnodes().iter() {
port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
add_node_dependency(&n... | attach | identifier_name |
pin_pt.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
#[test]
fn builds_altfn_gpio() {
with_parsed("
gpio {
0 {
p3@3 { direction = \"out\"; function = \"ad0_6\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap());
asse... | {
with_parsed("
gpio {
0 {
p2@2 { direction = \"out\"; }
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone(), cx);
super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_s... | identifier_body |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
/// Creates new view onto block from rlp.
pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> {
TransactionView {
rlp: rlp
}
}
/// Return reference to underlaying rlp.
pub fn rlp(&self) -> &Rlp<'a> {
&self.rlp
}
/// Get the nonce field of the transaction.
pub fn nonce(&self) -> U256 { self.rlp... | {
TransactionView {
rlp: Rlp::new(bytes)
}
} | identifier_body |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | // GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! View onto transaction rlp
use util::{U256, Bytes, Hashable, H256};
use rlp::{Rlp, View};
/// View onto transaction rlp.
pub struc... | // Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | random_line_split |
transaction.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (bytes: &'a [u8]) -> TransactionView<'a> {
TransactionView {
rlp: Rlp::new(bytes)
}
}
/// Creates new view onto block from rlp.
pub fn new_from_rlp(rlp: Rlp<'a>) -> TransactionView<'a> {
TransactionView {
rlp: rlp
}
}
/// Return reference to underlaying rlp.
pub fn rlp(&self) -> &Rlp<'a> {
&self... | new | identifier_name |
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct | {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10;
Some(ret)
}
}
}
}
#[derive(Copy, Clone)]
enum Lu... | Digits | identifier_name |
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct Digits {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10... | {
assert!(luhn_test(49927398716));
assert!(!luhn_test(49927398717));
assert!(!luhn_test(1234567812345678));
assert!(luhn_test(1234567812345670));
} | identifier_body | |
luhn_test.rs | // Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
struct Digits {
m: u64
}
impl Iterator for Digits {
type Item = u64;
fn next(&mut self) -> Option<u64> {
match self.m {
0 => None,
n => {
let ret = n % 10;
self.m = n / 10... | assert!(!luhn_test(49927398717));
assert!(!luhn_test(1234567812345678));
assert!(luhn_test(1234567812345670));
} | fn test_inputs() {
assert!(luhn_test(49927398716)); | random_line_split |
mod.rs | //! Collectors will receive events from the contextual shard, check if the
//! filter lets them pass, and collects if the receive, collect, or time limits
//! are not reached yet.
use std::sync::Arc;
mod error;
pub use error::Error as CollectorError;
#[cfg(feature = "unstable_discord_api")]
pub mod component_interac... | pub(crate) struct LazyArc<'a, T> {
value: &'a T,
arc: Option<Arc<T>>,
}
impl<'a, T: Clone> LazyArc<'a, T> {
pub fn new(value: &'a T) -> Self {
LazyArc {
value,
arc: None,
}
}
pub fn as_arc(&mut self) -> Arc<T> {
let value = self.value;
self.a... | /// the value in filters while only cloning values that actually match.
#[derive(Debug)] | random_line_split |
mod.rs | //! Collectors will receive events from the contextual shard, check if the
//! filter lets them pass, and collects if the receive, collect, or time limits
//! are not reached yet.
use std::sync::Arc;
mod error;
pub use error::Error as CollectorError;
#[cfg(feature = "unstable_discord_api")]
pub mod component_interac... |
}
| {
self.value
} | identifier_body |
mod.rs | //! Collectors will receive events from the contextual shard, check if the
//! filter lets them pass, and collects if the receive, collect, or time limits
//! are not reached yet.
use std::sync::Arc;
mod error;
pub use error::Error as CollectorError;
#[cfg(feature = "unstable_discord_api")]
pub mod component_interac... | (&mut self) -> Arc<T> {
let value = self.value;
self.arc.get_or_insert_with(|| Arc::new(value.clone())).clone()
}
}
impl<'a, T> std::ops::Deref for LazyArc<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.value
}
}
| as_arc | identifier_name |
window_event.rs | #![allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Serialize, Deserialize)]
pub enum WindowEvent {
Pos(i32, i32),
Size(u32, u32),
Close,
Refresh,
Focus(bool),
Iconify(bool),
FramebufferSize(u32, u32),
MouseButton(MouseButton, Action, Modifiers),
CursorPos(f6... | (&self) -> bool {
matches!(
self,
MouseButton(..) | CursorPos(..) | CursorEnter(..) | Scroll(..)
)
}
/// Tests if this event is related to the touch.
pub fn is_touch_event(&self) -> bool {
matches!(self, Touch(..))
}
}
// NOTE: list of keys inspired from... | is_mouse_event | identifier_name |
window_event.rs | #![allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Serialize, Deserialize)]
pub enum WindowEvent {
Pos(i32, i32),
Size(u32, u32),
Close,
Refresh,
Focus(bool),
Iconify(bool),
FramebufferSize(u32, u32),
MouseButton(MouseButton, Action, Modifiers),
CursorPos(f6... | }
use WindowEvent::*;
impl WindowEvent {
/// Tests if this event is related to the keyboard.
pub fn is_keyboard_event(&self) -> bool {
matches!(self, Key(..) | Char(..) | CharModifiers(..))
}
/// Tests if this event is related to the mouse.
pub fn is_mouse_event(&self) -> bool {
ma... | CharModifiers(char, Modifiers),
Touch(u64, f64, f64, TouchAction, Modifiers), | random_line_split |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use cra... | ,
}
}
}
| {
let document = Document::new(
&self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
Some(content_type),
... | conditional_block |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use cra... | &self.window,
HasBrowsingContext::No,
Some(url.clone()),
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
Some(content_type),
None,
DocumentActivity::Inac... | Text_xml | Application_xml | Application_xhtml_xml => {
let document = Document::new( | random_line_split |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use cra... |
}
impl DOMParserMethods for DOMParser {
// https://w3c.github.io/DOM-Parsing/#the-domparser-interface
fn ParseFromString(
&self,
s: DOMString,
ty: DOMParserBinding::SupportedType,
) -> Fallible<DomRoot<Document>> {
let url = self.window.get_url();
let content_type =... | {
Ok(DOMParser::new(window))
} | identifier_body |
domparser.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 crate::document_loader::DocumentLoader;
use crate::dom::bindings::codegen::Bindings::DOMParserBinding;
use cra... | (window: &Window) -> Fallible<DomRoot<DOMParser>> {
Ok(DOMParser::new(window))
}
}
impl DOMParserMethods for DOMParser {
// https://w3c.github.io/DOM-Parsing/#the-domparser-interface
fn ParseFromString(
&self,
s: DOMString,
ty: DOMParserBinding::SupportedType,
) -> Falli... | Constructor | identifier_name |
builtins.rs | use crate::state::InterpState;
use enum_iterator::IntoEnumIterator;
/// Represents a builtin function
#[derive(Debug, Clone, PartialEq, IntoEnumIterator)]
pub enum Builtin {
Dot,
Plus,
Minus,
Star,
Slash,
Abs,
And,
Or,
Xor,
LShift,
RShift,
Equals,
NotEquals,
Less... | (&self) -> &'static str {
match *self {
Builtin::Dot => ".",
Builtin::Plus => "+",
Builtin::Minus => "-",
Builtin::Star => "*",
Builtin::Slash => "/",
Builtin::Abs => "abs",
Builtin::And => "and",
Builtin::Or => "or"... | word | identifier_name |
builtins.rs | use crate::state::InterpState;
use enum_iterator::IntoEnumIterator;
/// Represents a builtin function
#[derive(Debug, Clone, PartialEq, IntoEnumIterator)]
pub enum Builtin {
Dot,
Plus,
Minus,
Star,
Slash,
Abs,
And,
Or,
Xor,
LShift,
RShift,
Equals,
NotEquals,
Less... | LessEqual => stackexpr!(|n2: i32, n1: i32| n1 <= n2),
GreaterEqual => stackexpr!(|n2: i32, n1: i32| n1 >= n2),
Emit => print!("{}", stack.pop::<char>()),
Dup => {
let n: i32 = stack.peak();
stack.push(n);
}
Swap => s... | RShift => stackexpr!(|u: i32, n: i32| n >> u),
Equals => stackexpr!(|n2: i32, n1: i32| n1 == n2),
NotEquals => stackexpr!(|n2: i32, n1: i32| n1 != n2),
LessThan => stackexpr!(|n2: i32, n1: i32| n1 < n2),
GreaterThan => stackexpr!(|n2: i32, n1: i32| n1 > n2), | random_line_split |
builtins.rs | use crate::state::InterpState;
use enum_iterator::IntoEnumIterator;
/// Represents a builtin function
#[derive(Debug, Clone, PartialEq, IntoEnumIterator)]
pub enum Builtin {
Dot,
Plus,
Minus,
Star,
Slash,
Abs,
And,
Or,
Xor,
LShift,
RShift,
Equals,
NotEquals,
Less... | Dot => print!("{}", stack.pop::<i32>()),
Plus => stackexpr!(|n2: i32, n1: i32| n1 + n2),
Minus => stackexpr!(|n2: i32, n1: i32| n1 - n2),
Star => stackexpr!(|n2: i32, n1: i32| n1 * n2),
Slash => stackexpr!(|n2: i32, n1: i32| n1 / n2),
Abs => stacke... | {
let stack = &mut state.stack;
/// Allows defining a builtin using closure-like syntax. Note that the
/// arguments are in reverse order, as that is how the stack is laid out.
macro_rules! stackexpr {
( | $($aname:ident : $atype:ty),+ | $($value:expr),+ ) => {
... | identifier_body |
lib.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/. */
#![crate_name = "js"]
#![crate_type = "rlib"]
#![feature(core_intrinsics)]
#![feature(link_args)]
#![feature(str_... |
pub mod jsapi;
pub mod linkhack;
pub mod rust;
pub mod glue;
pub mod jsval;
use jsapi::{JSContext, JSProtoKey, Heap};
use jsval::JSVal;
use rust::GCMethods;
use libc::c_uint;
use heapsize::HeapSizeOf;
pub const default_heapsize: u32 = 32_u32 * 1024_u32 * 1024_u32;
pub const default_stacksize: usize = 8192;
pub co... | #[macro_use]
extern crate heapsize;
extern crate rustc_serialize as serialize; | random_line_split |
lib.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/. */
#![crate_name = "js"]
#![crate_type = "rlib"]
#![feature(core_intrinsics)]
#![feature(link_args)]
#![feature(str_... |
// This is measured properly by the heap measurement implemented in SpiderMonkey.
impl<T: Copy + GCMethods<T>> HeapSizeOf for Heap<T> {
fn heap_size_of_children(&self) -> usize {
0
}
}
known_heap_size!(0, JSVal);
| {
*vp
} | identifier_body |
lib.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/. */
#![crate_name = "js"]
#![crate_type = "rlib"]
#![feature(core_intrinsics)]
#![feature(link_args)]
#![feature(str_... | (&self) -> usize {
0
}
}
known_heap_size!(0, JSVal);
| heap_size_of_children | identifier_name |
window.rs | -> &mut glfw::Window {
&mut self.window
}
/// The window width.
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
/// The window height.
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
... | verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST)); | random_line_split | |
window.rs |
/// This is the main interface with the 3d engine.
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_ms_per_frame: ... |
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis... | {
self.scene.add_trimesh(descr, scale)
} | identifier_body |
window.rs |
/// This is the main interface with the 3d engine.
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_ms_per_frame: ... | (&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_co... | add_sphere | identifier_name |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
us... | <T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
/// Allocat... | UnorderedHandle | identifier_name |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
us... |
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().ite... | { 1 } | identifier_body |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
us... | }
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
} | /// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
} | random_line_split |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... |
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.man... | {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
} | identifier_body |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... | }
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new... | sources: RefCell<SourceMap<'cfg>>, | random_line_split |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... | {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [... | Package | identifier_name |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... |
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from sour... | {
return Ok(pkg)
} | conditional_block |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a no... | // This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
}
| interrupted() {
| identifier_name |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a no... | #[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&se... | unsafe { czmq_sys::zsys_interrupted == 1 }
}
}
| random_line_split |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a no... |
}
#[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description... | {
unsafe { czmq_sys::zsys_interrupted == 1 }
} | identifier_body |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implemen... | {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", ha... | identifier_body | |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implemen... | () {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}",... | main | identifier_name |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
|
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn main() {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
... | // This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library. | random_line_split |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
... | {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics... | identifier_body |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(... | expand_deriving_from_primitive | identifier_name |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
... | methods: vec!( | random_line_split |
sync.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 self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.... | identifier_body |
sync.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 ... | BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on t... | match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(), | random_line_split |
sync.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 mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.can... | {
Vec::new()
} | conditional_block |
sync.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 ... | (&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered... | drop_port | identifier_name |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | <'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 { return None }
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Som... | shift_mut_ref | identifier_name |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... |
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &... | {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
... | identifier_body |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64... | Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR, | random_line_split |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... |
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
}
| { return None } | conditional_block |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn new(ip: String, date: String, req: String, code: i32, size: i32, ... |
}
| {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
} | identifier_body |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn | (ip: String, date: String, req: String, code: i32, size: i32, referer: String, agent: String) -> Weblog {
Weblog { ip: ip, date: date, req: req, code: code, size: size, referer: referer, agent: agent }
}
}
impl Eq for Weblog {}
impl PartialEq for Weblog {
fn eq(&self, other: &Self) -> bool {
s... | new | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.