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 |
|---|---|---|---|---|
redundant_else.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_ast::ast::{Block, Expr, ExprKind, Stmt, StmtKind};
use rustc_ast::visit::{walk_expr, Visitor};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy... | // else if else
ExprKind::If(_, next_then, Some(next_els)) => {
then = next_then;
els = next_els;
continue;
},
// else if without else
ExprKind::If(..) => return,
/... | {
if in_external_macro(cx.sess, stmt.span) {
return;
}
// Only look at expressions that are a whole statement
let expr: &Expr = match &stmt.kind {
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr,
_ => return,
};
// if else
l... | identifier_body |
redundant_else.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_ast::ast::{Block, Expr, ExprKind, Stmt, StmtKind};
use rustc_ast::visit::{walk_expr, Visitor};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_middle::lint::in_external_macro;
use rustc_session::{declare_lint_pass, declare_tool_lint};
declare_clippy... | } | } | random_line_split |
debug.rs | use winapi::um::{d3d11, d3d11_1, d3dcommon};
use wio::{com::ComPtr, wide::ToWide};
use std::{env, ffi::OsStr, fmt};
#[must_use]
pub struct DebugScope {
annotation: ComPtr<d3d11_1::ID3DUserDefinedAnnotation>,
}
impl DebugScope {
// TODO: Not used currently in release, will be used in the future
#[allow(d... | (&mut self) {
unsafe {
self.annotation.EndEvent();
}
}
}
pub fn debug_marker(context: &ComPtr<d3d11::ID3D11DeviceContext>, name: &str) {
// same here
if unsafe { context.GetType() } == d3d11::D3D11_DEVICE_CONTEXT_DEFERRED {
if env::var("GFX_NO_RENDERDOC").is_ok() {
... | drop | identifier_name |
debug.rs | use winapi::um::{d3d11, d3d11_1, d3dcommon};
use wio::{com::ComPtr, wide::ToWide};
use std::{env, ffi::OsStr, fmt};
#[must_use]
pub struct DebugScope {
annotation: ComPtr<d3d11_1::ID3DUserDefinedAnnotation>,
}
impl DebugScope {
// TODO: Not used currently in release, will be used in the future
#[allow(d... |
pub fn verify_debug_ascii(name: &str) -> bool {
let res = name.is_ascii();
if!res {
error!("DX11 buffer names must be ASCII");
}
res
}
/// Set the debug name of a resource.
///
/// Must be ASCII.
///
/// SetPrivateData will copy the data internally so the data doesn't need to live.
pub fn set... | {
// same here
if unsafe { context.GetType() } == d3d11::D3D11_DEVICE_CONTEXT_DEFERRED {
if env::var("GFX_NO_RENDERDOC").is_ok() {
return;
}
}
let annotation = context
.cast::<d3d11_1::ID3DUserDefinedAnnotation>()
.unwrap();
let msg: &OsStr = name.as_ref(... | identifier_body |
debug.rs | use winapi::um::{d3d11, d3d11_1, d3dcommon};
use wio::{com::ComPtr, wide::ToWide};
use std::{env, ffi::OsStr, fmt};
#[must_use]
pub struct DebugScope {
annotation: ComPtr<d3d11_1::ID3DUserDefinedAnnotation>,
}
impl DebugScope {
// TODO: Not used currently in release, will be used in the future
#[allow(d... |
res
}
/// Set the debug name of a resource.
///
/// Must be ASCII.
///
/// SetPrivateData will copy the data internally so the data doesn't need to live.
pub fn set_debug_name(resource: &d3d11::ID3D11DeviceChild, name: &str) {
unsafe {
resource.SetPrivateData(
(&d3dcommon::WKPDID_D3DDebugO... | {
error!("DX11 buffer names must be ASCII");
} | conditional_block |
debug.rs | use winapi::um::{d3d11, d3d11_1, d3dcommon};
use wio::{com::ComPtr, wide::ToWide};
use std::{env, ffi::OsStr, fmt};
#[must_use]
pub struct DebugScope {
annotation: ComPtr<d3d11_1::ID3DUserDefinedAnnotation>,
}
impl DebugScope {
// TODO: Not used currently in release, will be used in the future
#[allow(d... | /// Must be ASCII.
///
/// The given string will be mutated to add the suffix, then restored to it's original state.
/// This saves an allocation. SetPrivateData will copy the data internally so the data doesn't need to live.
pub fn set_debug_name_with_suffix(
resource: &d3d11::ID3D11DeviceChild,
name: &mut Str... |
/// Set the debug name of a resource with a given suffix.
/// | random_line_split |
edge-trigger-test.rs | /// Ensure all sockets operate on edge trigger mode.
extern crate amy;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::str;
use std::io::{Read, Write};
use amy::{
Poller,
Event,
};
const IP: &'static str = "127.0.0.1:10008";
/// This test ensures that only one write event is received, eve... | sock.set_nonblocking(true).unwrap();
// Create the poller and registrar
let mut poller = Poller::new().unwrap();
let registrar = poller.get_registrar();
// The socket should become writable once it's connected
let id = registrar.register(&sock, Event::Write).unwrap();
let notifications = p... | {
// Spawn a listening thread and accept one connection
thread::spawn(|| {
let listener = TcpListener::bind(IP).unwrap();
let (mut sock, _) = listener.accept().unwrap();
// When the test completes, the client will send a "stop" message to shutdown the server.
let mut buf = Strin... | identifier_body |
edge-trigger-test.rs | /// Ensure all sockets operate on edge trigger mode.
extern crate amy;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::str;
use std::io::{Read, Write};
use amy::{
Poller,
Event,
};
const IP: &'static str = "127.0.0.1:10008";
/// This test ensures that only one write event is received, eve... | () {
// Spawn a listening thread and accept one connection
thread::spawn(|| {
let listener = TcpListener::bind(IP).unwrap();
let (mut sock, _) = listener.accept().unwrap();
// When the test completes, the client will send a "stop" message to shutdown the server.
let mut buf = St... | edge_trigger | identifier_name |
edge-trigger-test.rs | /// Ensure all sockets operate on edge trigger mode.
extern crate amy;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::str;
use std::io::{Read, Write};
use amy::{
Poller,
Event, | /// triggered system, write events would come on every poll.
#[test]
fn edge_trigger() {
// Spawn a listening thread and accept one connection
thread::spawn(|| {
let listener = TcpListener::bind(IP).unwrap();
let (mut sock, _) = listener.accept().unwrap();
// When the test completes, th... | };
const IP: &'static str = "127.0.0.1:10008";
/// This test ensures that only one write event is received, even if no data is written. On a level | random_line_split |
edge-trigger-test.rs | /// Ensure all sockets operate on edge trigger mode.
extern crate amy;
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::str;
use std::io::{Read, Write};
use amy::{
Poller,
Event,
};
const IP: &'static str = "127.0.0.1:10008";
/// This test ensures that only one write event is received, eve... |
}
sock.set_nonblocking(true).unwrap();
// Create the poller and registrar
let mut poller = Poller::new().unwrap();
let registrar = poller.get_registrar();
// The socket should become writable once it's connected
let id = registrar.register(&sock, Event::Write).unwrap();
let notificati... | {
sock = s;
break;
} | conditional_block |
iter.rs | //! Collection of iterators over a graph.
//!
//! This module contains various iterators, meant to be returned from the different
//! iterator functions.
use std::collections::HashMap;
use std::collections::btree_map::Iter as BTreeIter;
use std::cell::Ref;
use graph::graph::Element;
use vec_map::Keys;
macro_rules! i... |
res
}
}
| {self.start = t;} | conditional_block |
iter.rs | //! Collection of iterators over a graph.
//!
//! This module contains various iterators, meant to be returned from the different
//! iterator functions.
use std::collections::HashMap;
use std::collections::btree_map::Iter as BTreeIter;
use std::cell::Ref;
use graph::graph::Element;
use vec_map::Keys;
macro_rules! i... | (tree : Ref<'a, HashMap<usize, Option<usize>>>, start : usize) -> Root<'a> {
Root {tree : tree, start : start}
}
}
impl<'a, E : 'a> Iterator for ConnIdVal<'a, E> {
type Item = (usize, &'a E);
fn next(&mut self) -> Option<(usize, &'a E)> {
self.element.next().map(|(&n, e)| (n, e))
}
}
i... | new | identifier_name |
iter.rs | //! Collection of iterators over a graph.
//!
//! This module contains various iterators, meant to be returned from the different
//! iterator functions.
use std::collections::HashMap;
use std::collections::btree_map::Iter as BTreeIter;
use std::cell::Ref;
use graph::graph::Element;
use vec_map::Keys;
macro_rules! i... |
}
impl<'a, E : 'a> Iterator for ConnIdVal<'a, E> {
type Item = (usize, &'a E);
fn next(&mut self) -> Option<(usize, &'a E)> {
self.element.next().map(|(&n, e)| (n, e))
}
}
impl<'a, E : 'a> Iterator for IterEdges<'a, E> {
type Item = &'a E;
fn next(&mut self) -> Option<&'a E> {
sel... | {
Root {tree : tree, start : start}
} | identifier_body |
iter.rs | //! Collection of iterators over a graph.
//!
//! This module contains various iterators, meant to be returned from the different
//! iterator functions.
use std::collections::HashMap;
use std::collections::btree_map::Iter as BTreeIter;
use std::cell::Ref;
use graph::graph::Element;
use vec_map::Keys;
macro_rules! i... | impl<'a, V : 'a, E : 'a> Iterator for ListIds<'a, V, E> {
type Item = usize;
fn next(&mut self) -> Option<usize> {
self.element.next()
}
}
impl<'a> Iterator for Root<'a> {
type Item = usize;
fn next(&mut self) -> Option<usize> {
let res = self.tree.get(&self.start).and_then(|&t| t);... | random_line_split | |
hidclass.rs | // Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according ... | reportId: UCHAR,
}}
pub type PHID_XFER_PACKET = *mut HID_XFER_PACKET;
//FIXME Stuff for NT_INCLUDED
STRUCT!{struct HID_COLLECTION_INFORMATION {
DescriptorSize: ULONG,
Polled: BOOLEAN,
Reserved1: [UCHAR; 1],
VendorID: USHORT,
ProductID: USHORT,
VersionNumber: USHORT,
}}
pub type PHID_COLLECTI... | random_line_split | |
termbox.rs | #[link(name = "termbox", vers = "0.1.0")];
#[crate_type = "lib"];
/*!
*
* A lightweight curses alternative wrapping the termbox library.
*
* # SYNOPSIS
*
* A hello world for the terminal:
*
* extern mod std;
* extern mod termbox;
*
* use tb = termbox;
*
* fn main() {
* tb::init();... | () {
ff::tb_shutdown();
}
pub fn width() -> uint {
ff::tb_width() as uint
}
pub fn height() -> uint {
ff::tb_height() as uint
}
/**
* Clear buffer.
*/
pub fn clear() {
ff::tb_clear();
}
/**
* Write buffer to terminal.
*/
pub fn present() {
ff::tb_present();
}
pub fn set_cursor(cx: int... | shutdown | identifier_name |
termbox.rs | #[link(name = "termbox", vers = "0.1.0")];
#[crate_type = "lib"];
/*!
*
* A lightweight curses alternative wrapping the termbox library.
*
* # SYNOPSIS
*
* A hello world for the terminal:
*
* extern mod std;
* extern mod termbox;
*
* use tb = termbox;
*
* fn main() {
* tb::init();... |
pub fn height() -> uint {
ff::tb_height() as uint
}
/**
* Clear buffer.
*/
pub fn clear() {
ff::tb_clear();
}
/**
* Write buffer to terminal.
*/
pub fn present() {
ff::tb_present();
}
pub fn set_cursor(cx: int, cy: int) {
ff::tb_set_cursor(cx as c_int, cy as c_int);
}
// low-level wrappe... | {
ff::tb_width() as uint
} | identifier_body |
termbox.rs | #[link(name = "termbox", vers = "0.1.0")];
#[crate_type = "lib"];
/*!
*
* A lightweight curses alternative wrapping the termbox library.
*
* # SYNOPSIS
*
* A hello world for the terminal:
*
* extern mod std;
* extern mod termbox;
*
* use tb = termbox;
*
* fn main() {
* tb::init();... |
fn tb_peek_event(ev: *raw_event, timeout: c_uint) -> c_int;
fn tb_poll_event(ev: *raw_event) -> c_int;
}
pub fn init() -> int {
ff::tb_init() as int
}
pub fn shutdown() {
ff::tb_shutdown();
}
pub fn width() -> uint {
ff::tb_width() as uint
}
pub fn height() -> uint {
ff::tb_height() as ... |
fn tb_change_cell(x: c_uint, y: c_uint, ch: u32, fg: u16, bg: u16);
fn tb_select_input_mode(mode: c_int) -> c_int;
fn tb_set_clear_attributes(fg: u16, bg: u16); | random_line_split |
mod_resolver.rs | use std::io;
use std::path::PathBuf;
use super::read_config;
use crate::{FileName, Input, Session};
fn verify_mod_resolution(input_file_name: &str, exp_misformatted_files: &[&str]) {
let input_file = PathBuf::from(input_file_name);
let config = read_config(&input_file);
let mut session = Session::<io::St... | () {
// See also https://github.com/rust-lang/rustfmt/issues/5063
verify_mod_resolution(
"tests/mod-resolver/issue-5063/main.rs",
&[
"tests/mod-resolver/issue-5063/foo/bar/baz.rs",
"tests/mod-resolver/issue-5063/foo.rs",
],
);
}
| out_of_line_nested_inline_within_out_of_line | identifier_name |
mod_resolver.rs | use std::io;
use std::path::PathBuf;
use super::read_config;
use crate::{FileName, Input, Session};
fn verify_mod_resolution(input_file_name: &str, exp_misformatted_files: &[&str]) {
let input_file = PathBuf::from(input_file_name);
let config = read_config(&input_file);
let mut session = Session::<io::St... |
#[test]
fn out_of_line_nested_inline_within_out_of_line() {
// See also https://github.com/rust-lang/rustfmt/issues/5063
verify_mod_resolution(
"tests/mod-resolver/issue-5063/main.rs",
&[
"tests/mod-resolver/issue-5063/foo/bar/baz.rs",
"tests/mod-resolver/issue-5063/foo... | {
// See also https://github.com/rust-lang/rustfmt/issues/4874
verify_mod_resolution(
"tests/mod-resolver/issue-4874/main.rs",
&[
"tests/mod-resolver/issue-4874/bar/baz.rs",
"tests/mod-resolver/issue-4874/foo/qux.rs",
],
);
} | identifier_body |
mod_resolver.rs | use std::io;
use std::path::PathBuf;
use super::read_config;
use crate::{FileName, Input, Session};
fn verify_mod_resolution(input_file_name: &str, exp_misformatted_files: &[&str]) {
let input_file = PathBuf::from(input_file_name);
let config = read_config(&input_file);
let mut session = Session::<io::St... | );
}
#[test]
fn out_of_line_nested_inline_within_out_of_line() {
// See also https://github.com/rust-lang/rustfmt/issues/5063
verify_mod_resolution(
"tests/mod-resolver/issue-5063/main.rs",
&[
"tests/mod-resolver/issue-5063/foo/bar/baz.rs",
"tests/mod-resolver/issue-... | "tests/mod-resolver/issue-4874/bar/baz.rs",
"tests/mod-resolver/issue-4874/foo/qux.rs",
], | random_line_split |
filecache_test.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::cache::cache::Cache;
use crate::cache::filecache::Filecache;
use std::fs;
use std::path::Path;
#[test]
fn test_dircache() {
use std::env;
... | let _ = f.read_to_string(&mut s);
});
assert_eq!(&s, "0123456789");
} | let mut s = String::new();
cache.read(path, |f| { | random_line_split |
filecache_test.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::cache::cache::Cache;
use crate::cache::filecache::Filecache;
use std::fs;
use std::path::Path;
#[test]
fn | () {
use std::env;
let mut dir = env::temp_dir();
dir.push("t_rex_test");
let basepath = format!("{}", &dir.display());
let _ = fs::remove_dir_all(&basepath);
let cache = Filecache {
basepath: basepath,
baseurl: Some("http://localhost:6767".to_string()),
};
let path = "... | test_dircache | identifier_name |
filecache_test.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::cache::cache::Cache;
use crate::cache::filecache::Filecache;
use std::fs;
use std::path::Path;
#[test]
fn test_dircache() | let _ = cache.write(path, obj.as_bytes());
assert!(Path::new(&fullpath).exists());
// Cache hit
assert_eq!(cache.read(path, |_| {}), true);
// Read from cache
let mut s = String::new();
cache.read(path, |f| {
let _ = f.read_to_string(&mut s);
});
assert_eq!(&s, "0123456789"... | {
use std::env;
let mut dir = env::temp_dir();
dir.push("t_rex_test");
let basepath = format!("{}", &dir.display());
let _ = fs::remove_dir_all(&basepath);
let cache = Filecache {
basepath: basepath,
baseurl: Some("http://localhost:6767".to_string()),
};
let path = "til... | identifier_body |
itemrt.rs | //! Item rare tables for GC/BB. The ItemRT.gsl is organized much in the same
//! way as the ItemPT archive.
use std::io::{Read, Write, Cursor};
use std::io;
use psoserial::Serial;
use psoserial::util::*;
/// Parsed rare table entry. There are 101 Enemy entries and 30 Box entries in
/// a full rare table file.
#[deri... | {
pub enemy_rares: Vec<RtEntry>,
pub box_rares: Vec<RtEntry>
}
impl Serial for RtSet {
fn serialize(&self, dst: &mut Write) -> io::Result<()> {
try!(write_array(&self.enemy_rares, 101, dst));
try!(write_array(&self.box_rares, 30, dst));
Ok(())
}
fn deserialize(src: &mut Rea... | RtSet | identifier_name |
itemrt.rs | //! Item rare tables for GC/BB. The ItemRT.gsl is organized much in the same
//! way as the ItemPT archive.
use std::io::{Read, Write, Cursor};
use std::io;
use psoserial::Serial;
use psoserial::util::*;
/// Parsed rare table entry. There are 101 Enemy entries and 30 Box entries in
/// a full rare table file.
#[deri... |
}
/// Full rare drop table for a full episode.
#[derive(Clone, Debug)]
pub struct ItemRT {
sections: Vec<RtSet>
}
impl ItemRT {
pub fn load_from_buffers(files: &[&[u8]]) -> io::Result<ItemRT> {
if files.len()!= 10 {
return Err(io::Error::new(io::ErrorKind::Other, "Not enough files, need 1... | {
let enemy_rares = try!(read_array(101, src));
let box_rares = try!(read_array(30, src));
Ok(RtSet {
enemy_rares: enemy_rares,
box_rares: box_rares
})
} | identifier_body |
itemrt.rs | //! Item rare tables for GC/BB. The ItemRT.gsl is organized much in the same
//! way as the ItemPT archive.
use std::io::{Read, Write, Cursor};
use std::io;
use psoserial::Serial;
use psoserial::util::*;
/// Parsed rare table entry. There are 101 Enemy entries and 30 Box entries in
/// a full rare table file.
#[deri... | Ok(())
}
fn deserialize(src: &mut Read) -> io::Result<Self> {
Ok(RtEntry {
prob: try!(Serial::deserialize(src)),
item_data: try!(Serial::deserialize(src))
})
}
}
impl RtEntry {
/// Derive the drop probability from the encoded value.
///
/// This ... | try!(self.item_data.serialize(dst)); | random_line_split |
TestSin.rs | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 app... | }
float2 __attribute__((kernel)) testSinFloat2Float2(float2 in) {
return sin(in);
}
float3 __attribute__((kernel)) testSinFloat3Float3(float3 in) {
return sin(in);
}
float4 __attribute__((kernel)) testSinFloat4Float4(float4 in) {
return sin(in);
} | random_line_split | |
context.rs | use alloc::arc::Arc;
use alloc::boxed::Box;
use alloc::{BTreeMap, Vec, VecDeque};
use core::cmp::Ordering;
use core::mem;
use spin::Mutex;
use context::arch;
use context::file::FileDescriptor;
use context::memory::{Grant, Memory, SharedMemory, Tls};
use device;
use scheme::{SchemeNamespace, FileHandle};
use syscall::d... | pub image: Vec<SharedMemory>,
/// User heap
pub heap: Option<SharedMemory>,
/// User stack
pub stack: Option<Memory>,
/// User signal stack
pub sigstack: Option<Memory>,
/// User Thread local storage
pub tls: Option<Tls>,
/// User grants
pub grants: Arc<Mutex<Vec<Grant>>>,
... | /// Restore ksig context on next switch
pub ksig_restore: bool,
/// Executable image | random_line_split |
context.rs | use alloc::arc::Arc;
use alloc::boxed::Box;
use alloc::{BTreeMap, Vec, VecDeque};
use core::cmp::Ordering;
use core::mem;
use spin::Mutex;
use context::arch;
use context::file::FileDescriptor;
use context::memory::{Grant, Memory, SharedMemory, Tls};
use device;
use scheme::{SchemeNamespace, FileHandle};
use syscall::d... | (&self, file: FileDescriptor, min: usize) -> Option<FileHandle> {
let mut files = self.files.lock();
for (i, file_option) in files.iter_mut().enumerate() {
if file_option.is_none() && i >= min {
*file_option = Some(file);
return Some(FileHandle::from(i));
... | add_file_min | identifier_name |
context.rs | use alloc::arc::Arc;
use alloc::boxed::Box;
use alloc::{BTreeMap, Vec, VecDeque};
use core::cmp::Ordering;
use core::mem;
use spin::Mutex;
use context::arch;
use context::file::FileDescriptor;
use context::memory::{Grant, Memory, SharedMemory, Tls};
use device;
use scheme::{SchemeNamespace, FileHandle};
use syscall::d... |
/// Add a file to the lowest available slot greater than or equal to min.
/// Return the file descriptor number or None if no slot was found
pub fn add_file_min(&self, file: FileDescriptor, min: usize) -> Option<FileHandle> {
let mut files = self.files.lock();
for (i, file_option) in files... | {
self.add_file_min(file, 0)
} | identifier_body |
context.rs | use alloc::arc::Arc;
use alloc::boxed::Box;
use alloc::{BTreeMap, Vec, VecDeque};
use core::cmp::Ordering;
use core::mem;
use spin::Mutex;
use context::arch;
use context::file::FileDescriptor;
use context::memory::{Grant, Memory, SharedMemory, Tls};
use device;
use scheme::{SchemeNamespace, FileHandle};
use syscall::d... |
} else {
None
}
}
/// Remove a file
// TODO: adjust files vector to smaller size if possible
pub fn remove_file(&self, i: FileHandle) -> Option<FileDescriptor> {
let mut files = self.files.lock();
if i.into() < files.len() {
files[i.into()].take(... | {
None
} | conditional_block |
complex.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 test_div() {
assert_eq!(_neg1_1i / _0_1i, _1_1i);
for &c in all_consts.iter() {
if c!= Zero::zero() {
assert_eq!(c / c, _1_0i);
}
}
}
#[test]
fn test_neg() {
assert_eq!(-_1_0i + _0_1i, ... | assert_eq!(c * _1_0i, c);
assert_eq!(_1_0i * c, c);
}
}
#[test] | random_line_split |
complex.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 ... | () {
for &c in all_consts.iter() {
assert_eq!(c.conj(), Cmplx::new(c.re, -c.im));
assert_eq!(c.conj().conj(), c);
}
}
#[test]
fn test_inv() {
assert_eq!(_1_1i.inv(), _05_05i.conj());
assert_eq!(_1_0i.inv(), _1_0i.inv());
}
#[test]
#[shoul... | test_conj | identifier_name |
complex.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 ... |
}
impl<T: Clone + Real> Cmplx<T> {
/// Calculate the principal Arg of self.
#[inline]
pub fn arg(&self) -> T {
self.im.atan2(&self.re)
}
/// Convert to polar form (r, theta), such that `self = r * exp(i
/// * theta)`
#[inline]
pub fn to_polar(&self) -> (T, T) {
(self.no... | {
self.re.hypot(&self.im)
} | identifier_body |
complex.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 ... |
}
}
#[cfg(test)]
mod test {
#[allow(non_uppercase_statics)];
use super::*;
use std::num::{Zero,One,Real};
pub static _0_0i : Complex64 = Cmplx { re: 0.0, im: 0.0 };
pub static _1_0i : Complex64 = Cmplx { re: 1.0, im: 0.0 };
pub static _1_1i : Complex64 = Cmplx { re: 1.0, im: 1.0 };
p... | {
format!("{}+{}i", self.re.to_str_radix(radix), self.im.to_str_radix(radix))
} | conditional_block |
js.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/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of DOM objects whose lifetime is ent... |
}
impl<T: DomObject> JS<T> {
/// Create a JS<T> from a &T
#[allow(unrooted_must_root)]
pub fn from_ref(obj: &T) -> JS<T> {
debug_assert!(thread_state::get().is_script());
JS {
ptr: unsafe { NonZero::new(&*obj) },
}
}
}
impl<'root, T: DomObject + 'root> RootedRefere... | {
debug_assert!(thread_state::get().is_layout());
LayoutJS {
ptr: self.ptr.clone(),
}
} | identifier_body |
js.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/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of DOM objects whose lifetime is ent... | pub fn new(initial: &T) -> MutJS<T> {
debug_assert!(thread_state::get().is_script());
MutJS {
val: UnsafeCell::new(JS::from_ref(initial)),
}
}
/// Set this `MutJS` to the given value.
pub fn set(&self, val: &T) {
debug_assert!(thread_state::get().is_script())... | impl<T: DomObject> MutJS<T> {
/// Create a new `MutJS`. | random_line_split |
js.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/. */
//! Smart pointers for the JS-managed DOM objects.
//!
//! The DOM is made up of DOM objects whose lifetime is ent... | (tracer: *mut JSTracer) {
debug!("tracing stack roots");
STACK_ROOTS.with(|ref collection| {
let RootCollectionPtr(collection) = collection.get().unwrap();
let collection = &*(*collection).roots.get();
for root in collection {
trace_reflector(tracer, "on stack", &**root);
... | trace_roots | identifier_name |
lib.rs | #![feature(quote, plugin_registrar, rustc_private)]
#![feature(std_misc)]
extern crate syntax;
extern crate rustc;
extern crate tempdir;
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{PathBuf, Path};
use std::process;
use syntax::ast;
use syntax::codem... | (reg: &Registry, name: String, expander: F)
-> Result<base::SyntaxExtension, ()> {
let dir = match TempDir::new(&format!("rustc_external_mixin_{}", name)) {
Ok(d) => d,
Err(e) => {
reg.sess.span_err(reg.krate_span,
&format... | new | identifier_name |
lib.rs | #![feature(quote, plugin_registrar, rustc_private)]
#![feature(std_misc)]
extern crate syntax;
extern crate rustc;
extern crate tempdir;
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{PathBuf, Path};
use std::process;
use syntax::ast;
use syntax::codem... | &Path,
&Path) -> Result<Output, ()>
{
fn expand<'cx>(&self,
cx: &'cx mut ExtCtxt,
sp: codemap::Span,
raw_tts: &[ast::TokenTree])
-> Box<MacResult+'cx>
{
macro_rules! mac_try {... | random_line_split | |
lib.rs | #![feature(quote, plugin_registrar, rustc_private)]
#![feature(std_misc)]
extern crate syntax;
extern crate rustc;
extern crate tempdir;
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use std::fs::{self, File};
use std::path::{PathBuf, Path};
use std::process;
use syntax::ast;
use syntax::codem... | args.connect("`, `"),
e)
};
cx.span_err(sp, &msg);
Err(())
}
}
}
/// The options passed to the macro.
pub type Options = HashMap<String, Vec<(String, codemap::Span)>>;
pub enum Output {
Interpreted(process::Output),
... | {
let mut command = process::Command::new(&binary);
command.current_dir(dir)
.args(&args);
if let Some(file) = file {
command.arg(&file);
}
match command.output() {
Ok(o) => Ok(o),
Err(e) => {
let msg = if args.is_empty() {
format!("`{}!... | identifier_body |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::{anyhow, Error};
use async_trait::async_trait;
use bookmarks::BookmarkTransactionError;
use context::CoreContext;
use mononoke_... |
async fn into_transaction_hook(
self: Box<Self>,
_ctx: &CoreContext,
rebased: &RebasedChangesets,
) -> Result<Box<dyn PushrebaseTransactionHook>, Error> {
// Let's tie assigned git hashes to rebased Bonsai changesets:
let entries = self
.assignments
... | {
let git_sha1 = extract_git_sha1_from_bonsai_extra(
bcs_new
.extra
.iter()
.map(|(k, v)| (k.as_str(), v.as_slice())),
)?;
if let Some(git_sha1) = git_sha1 {
self.assignments.insert(bcs_old, git_sha1);
}
Ok((... | identifier_body |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::{anyhow, Error};
use async_trait::async_trait;
use bookmarks::BookmarkTransactionError;
use context::CoreContext;
use mononoke_... | (&self) -> Result<Box<dyn PushrebaseCommitHook>, Error> {
let hook = Box::new(GitMappingCommitHook {
bonsai_git_mapping: self.bonsai_git_mapping.clone(),
assignments: HashMap::new(),
}) as Box<dyn PushrebaseCommitHook>;
Ok(hook)
}
}
struct GitMappingCommitHook {
... | prepushrebase | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::{anyhow, Error};
use async_trait::async_trait;
use bookmarks::BookmarkTransactionError;
use context::CoreContext;
use mononoke_... | }
} | .await
.map_err(|e| BookmarkTransactionError::Other(e.into()))?;
Ok(txn) | random_line_split |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::{anyhow, Error};
use async_trait::async_trait;
use bookmarks::BookmarkTransactionError;
use context::CoreContext;
use mononoke_... |
Ok(Box::new(GitMappingTransactionHook {
bonsai_git_mapping: self.bonsai_git_mapping,
entries,
}) as Box<dyn PushrebaseTransactionHook>)
}
}
struct GitMappingTransactionHook {
bonsai_git_mapping: Arc<dyn BonsaiGitMapping>,
entries: Vec<BonsaiGitMappingEntry>,
}
#[a... | {
return Err(anyhow!(
"Git mapping rebased set ({}) and assignments ({}) have different lengths!",
rebased.len(),
self.assignments.len(),
));
} | conditional_block |
test_wait.rs | use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::signal::*;
use nix::sys::wait::*;
use libc::exit;
#[test]
fn test_wait_signal() |
#[test]
fn test_wait_exit() {
match fork() {
Ok(Child) => unsafe { exit(12); },
Ok(Parent { child }) => {
assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12)));
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!(... | {
match fork() {
Ok(Child) => pause().unwrap_or(()),
Ok(Parent { child }) => {
kill(child, SIGKILL).ok().expect("Error: Kill Failed");
assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, SIGKILL, false)));
},
// panic, fork should never fail unless there is a ... | identifier_body |
test_wait.rs | use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::signal::*;
use nix::sys::wait::*;
use libc::exit;
#[test]
fn | () {
match fork() {
Ok(Child) => pause().unwrap_or(()),
Ok(Parent { child }) => {
kill(child, SIGKILL).ok().expect("Error: Kill Failed");
assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, SIGKILL, false)));
},
// panic, fork should never fail unless there is... | test_wait_signal | identifier_name |
test_wait.rs | use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::signal::*;
use nix::sys::wait::*;
use libc::exit;
#[test]
fn test_wait_signal() {
match fork() {
Ok(Child) => pause().unwrap_or(()),
Ok(Parent { child }) => {
kill(child, SIGKILL).ok().expect("Error: Kill Failed");
as... | assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12)));
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!("Error: Fork Failed")
}
} | Ok(Child) => unsafe { exit(12); },
Ok(Parent { child }) => { | random_line_split |
baps3-load.rs | #![feature(plugin)]
extern crate baps3_protocol;
#[macro_use] extern crate baps3_cli;
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
#[plugin] #[no_link] extern crate docopt_macros;
use std::borrow::ToOwned;
use std::os;
use std::path;
use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos... | )));
try!(baps3.send(&Message::new("load").arg(&*ap)));
if flag_play {
try!(baps3.send(&Message::new("play")));
}
Ok(())
}
/// Converts a potentially-relative path string to an absolute path string.
fn to_absolute_path_str(rel: &str) -> Baps3Result<String> {
// This is a convoluted, enta... | { vec!["FileLoad"] } | conditional_block |
baps3-load.rs | #![feature(plugin)]
extern crate baps3_protocol;
#[macro_use] extern crate baps3_cli;
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
#[plugin] #[no_link] extern crate docopt_macros;
use std::borrow::ToOwned;
use std::os;
use std::path;
use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos... | use baps3_protocol::proto::Message;
docopt!(Args, "
Loads a file into a BAPS3 server.
Usage:
baps3-load -h
baps3-load [-pv] [-t <target>] <file>
Options:
-h, --help Show this message.
-p, --play If set, play the file upon loading.
-v, --verbose Prints a trail of miscellaneo... | random_line_split | |
baps3-load.rs | #![feature(plugin)]
extern crate baps3_protocol;
#[macro_use] extern crate baps3_cli;
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
#[plugin] #[no_link] extern crate docopt_macros;
use std::borrow::ToOwned;
use std::os;
use std::path;
use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos... | () {
let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit());
load(args).unwrap_or_else(|&:e| werr!("error: {}", e));
}
| main | identifier_name |
baps3-load.rs | #![feature(plugin)]
extern crate baps3_protocol;
#[macro_use] extern crate baps3_cli;
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
#[plugin] #[no_link] extern crate docopt_macros;
use std::borrow::ToOwned;
use std::os;
use std::path;
use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos... |
/// Converts a potentially-relative path string to an absolute path string.
fn to_absolute_path_str(rel: &str) -> Baps3Result<String> {
// This is a convoluted, entangled mess of Results and Options.
// I sincerely apologise.
let badpath = |&:| Baps3Error::InvalidPath { path: rel.to_owned() };
path:... | {
let ap = try!(to_absolute_path_str(&*arg_file));
let log = |&:s:&str| verbose_logger(flag_verbose, s);
let mut baps3 = try!(Baps3::new(log, &*flag_target,
&*(if flag_play { vec!["FileLoad", "PlayStop"] }
else { vec!["FileLoad"] })));
try!(baps3.send... | identifier_body |
proc-macro-crate-in-paths.rs | // Copyright 2018 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 ... | (input: TokenStream) -> TokenStream {
input
}
| derive_template | identifier_name |
proc-macro-crate-in-paths.rs | // Copyright 2018 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 ... | {
input
} | identifier_body | |
proc-macro-crate-in-paths.rs | // Copyright 2018 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 ... | #![crate_type = "proc-macro"]
#![deny(rust_2018_compatibility)]
#![feature(rust_2018_preview)]
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro_derive(Template, attributes(template))]
pub fn derive_template(input: TokenStream) -> TokenStream {
input
} | // compile-pass
// force-host
// no-prefer-dynamic
| random_line_split |
unique-send-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let (p, ch) = stream();
let ch = SharedChan::new(ch);
let n = 100u;
let mut expected = 0u;
for uint::range(0u, n) |i| {
let ch = ch.clone();
task::spawn(|| child(&ch, i) );
expected += i;
}
let mut actual = 0u;
for uint::range(0u, n) |_i| {
... | {
c.send(~i);
} | identifier_body |
unique-send-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
assert!(expected == actual);
} | } | random_line_split |
unique-send-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (c: &SharedChan<~uint>, i: uint) {
c.send(~i);
}
pub fn main() {
let (p, ch) = stream();
let ch = SharedChan::new(ch);
let n = 100u;
let mut expected = 0u;
for uint::range(0u, n) |i| {
let ch = ch.clone();
task::spawn(|| child(&ch, i) );
expected += i;
}
let mut... | child | identifier_name |
mod.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` architecture-specific implementation.
// pub ... | () {
asm!("movabsq $$(stack_top), %rsp");
asm!("mov ax, 0
mov ss, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
call arch_init"
:::: "intel");
}
/// Entry point for architecture-specific kernel init
///
/// This expects to be passed the addr... | long_mode_init | identifier_name |
mod.rs | // | // SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` architecture-specific implementation.
// pub mod... | random_line_split | |
mod.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` architecture-specific implementation.
// pub ... |
}
//-- enable flags needed for paging ------------------------------------
unsafe {
// control_regs::cr0::enable_write_protect(true);
// kinfoln!(dots: ". ", "Page write protect ENABED" );
let efer = msr::read(msr::IA32_EFER);
trace!("EFER = {:#x}", efer);
msr:... | { params.mem_map.push(a); } | conditional_block |
mod.rs | //
// SOS: the Stupid Operating System
// by Eliza Weisman (eliza@elizas.website)
//
// Copyright (c) 2015-2017 Eliza Weisman
// Released under the terms of the MIT license. See `LICENSE` in the root
// directory of this repository for more information.
//
//! `x86_64` architecture-specific implementation.
// pub ... |
/// Entry point for architecture-specific kernel init
///
/// This expects to be passed the address of a valid
/// Multiboot 2 info struct. It's the bootloader's responsibility to ensure
/// that this is passed in the correct register as expected by the calling
/// convention (`edi` on x86). If this isn't there, you ... | {
asm!("movabsq $$(stack_top), %rsp");
asm!("mov ax, 0
mov ss, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
call arch_init"
:::: "intel");
} | identifier_body |
imports.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {} }
mod bar { pub fn f() {} }
pub fn f() -> bool { true }
// Items and explicit imports shadow globs.
fn g() {
use foo::*;
use bar::*;
fn f() -> bool { true }
let _: bool = f();
}
fn h() {
use foo::*;
use bar::*;
use f;
let _: bool = f();
}
// Here, there appears to be shadowing ... | f | identifier_name |
imports.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let _: bool = f();
}
fn h() {
use foo::*;
use bar::*;
use f;
let _: bool = f();
}
// Here, there appears to be shadowing but isn't because of namespaces.
mod b {
use foo::*; // This imports `f` in the value namespace.
use super::b as f; // This imports `f` only in the type namespace,
... | { true } | identifier_body |
imports.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | use foo::*;
use bar::*;
fn f() -> bool { true }
let _: bool = f();
}
fn h() {
use foo::*;
use bar::*;
use f;
let _: bool = f();
}
// Here, there appears to be shadowing but isn't because of namespaces.
mod b {
use foo::*; // This imports `f` in the value namespace.
use super::b... |
// Items and explicit imports shadow globs.
fn g() { | random_line_split |
cmd.rs | use clap::{App, Arg};
use generators::common::{GenConfig, GenMode};
use itertools::Itertools;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct CommandLineArguments {
pub codegen_key: Option<String>,
pub demo_key: Option<String>,
pub bench_key: Option<String>,
pub generation_mode: GenMode,
... | let mut config = GenConfig::new();
if!config_string.is_empty() {
for mut chunk in &config_string.split(' ').chunks(2) {
let key = chunk.next().unwrap();
let value =
u64::from_str(chunk.next().expect("Bad config")).expect("Invalid config value");
config... | "special_random" => GenMode::SpecialRandom,
_ => panic!("Invalid generation mode"),
};
let config_string = matches.value_of("config").unwrap_or(""); | random_line_split |
cmd.rs | use clap::{App, Arg};
use generators::common::{GenConfig, GenMode};
use itertools::Itertools;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct CommandLineArguments {
pub codegen_key: Option<String>,
pub demo_key: Option<String>,
pub bench_key: Option<String>,
pub generation_mode: GenMode,
... | Arg::with_name("limit")
.short("l")
.long("limit")
.help("Specifies the maximum number of elements to generate")
.takes_value(true),
)
.arg(
Arg::with_name("out")
.short("o")
.long("out")
... | {
let matches = App::new(name)
.version("0.1.0")
.author("Mikhail Hogrefe <mikhailhogrefe@gmail.com>")
.about("Runs demos and benchmarks for malachite-base functions.")
.arg(
Arg::with_name("generation_mode")
.short("m")
.long("generation_m... | identifier_body |
cmd.rs | use clap::{App, Arg};
use generators::common::{GenConfig, GenMode};
use itertools::Itertools;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct | {
pub codegen_key: Option<String>,
pub demo_key: Option<String>,
pub bench_key: Option<String>,
pub generation_mode: GenMode,
pub config: GenConfig,
pub limit: usize,
pub out: String,
}
pub fn read_command_line_arguments(name: &str) -> CommandLineArguments {
let matches = App::new(name... | CommandLineArguments | identifier_name |
cabi.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 ... | (ty: Type, attr: option::Option<Attribute>) -> ArgType {
ArgType {
kind: Indirect,
ty: ty,
cast: option::None,
pad: option::None,
attr: attr
}
}
pub fn is_direct(&self) -> bool {
return self.kind == Direct;
}
pub fn is... | indirect | identifier_name |
cabi.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 ... |
}
/// Metadata describing how the arguments to a native function
/// should be passed in order to respect the native ABI.
///
/// I will do my best to describe this structure, but these
/// comments are reverse-engineered and may be inaccurate. -NDM
pub struct FnType {
/// The LLVM types of each argument.
arg... | {
return self.kind == Indirect;
} | identifier_body |
cabi.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | /// I will do my best to describe this structure, but these
/// comments are reverse-engineered and may be inaccurate. -NDM
pub struct FnType {
/// The LLVM types of each argument.
arg_tys: ~[ArgType],
/// LLVM return type.
ret_ty: ArgType,
}
pub fn compute_abi_info(ccx: &CrateContext,
... | random_line_split | |
lib.rs | //! [tui](https://github.com/fdehau/tui-rs) is a library used to build rich
//! terminal users interfaces and dashboards.
//!
//!
//!
//! # Get started
//!
//! ## Adding `tui` as a dependency
//!
//! ```toml
//! [dependencies]
//! tui = "0.17"
/... | //!
//! The same logic applies for all other available backends.
//!
//! ## Creating a `Terminal`
//!
//! Every application using `tui` should start by instantiating a `Terminal`. It is a light
//! abstraction over available backends that provides basic functionalities such as clearing the
//! screen, hiding the cursor... | //!
//! ``` | random_line_split |
file_dlg.rs | /* Copyright 2015 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use std::borrow::Cow;
use std::ffi::CStr;
use std::path::{PathBuf, Path};
... | () -> FileDlg {
unsafe {
::iup_open();
let ih = IupFileDlg();
FileDlg(HandleRc::new(ih))
}
}
pub fn dialog_type(&self) -> FileDialogType {
unsafe {
let val = get_str_attribute_slice(self.handle(), "DIALOGTYPE\0");
FileDialogTyp... | new | identifier_name |
file_dlg.rs | /* Copyright 2015 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use std::borrow::Cow;
use std::ffi::CStr;
use std::path::{PathBuf, Path};
... | }
}
pub fn value_multiple(&self) -> Option<Vec<PathBuf>> {
assert!(self.multiple_files());
unsafe {
let val = get_attribute_ptr(self.handle(), "VALUE\0");
if val.is_null() {
None
} else {
const PIPE: &'static [char] = &... | None
} else {
Some(PathBuf::from(&*CStr::from_ptr(val).to_string_lossy()))
} | random_line_split |
msgsend-ring-mutex-arcs.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 init() -> (pipe,pipe) {
let m = Arc::new((Mutex::new(Vec::new()), Condvar::new()));
((&m).clone(), m)
}
fn thread_ring(i: usize, count: usize, num_chan: pipe, num_port: pipe) {
let mut num_chan = Some(num_chan);
let mut num_port = Some(num_port);
// Send/Receive lots of messages.
for j in... | {
let &(ref lock, ref cond) = &**p;
let mut arr = lock.lock().unwrap();
while arr.is_empty() {
arr = cond.wait(arr).unwrap();
}
arr.pop().unwrap()
} | identifier_body |
msgsend-ring-mutex-arcs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (i: usize, count: usize, num_chan: pipe, num_port: pipe) {
let mut num_chan = Some(num_chan);
let mut num_port = Some(num_port);
// Send/Receive lots of messages.
for j in 0..count {
//println!("thread %?, iter %?", i, j);
let num_chan2 = num_chan.take().unwrap();
let num_port2 =... | thread_ring | identifier_name |
msgsend-ring-mutex-arcs.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 ... |
// all done, report stats.
let num_msgs = num_tasks * msg_per_task;
let rate = (num_msgs as f64) / (dur.as_secs() as f64);
println!("Sent {} messages in {:?}", num_msgs, dur);
println!(" {} messages / second", rate);
println!(" {} μs / message", 1000000. / rate);
} | }); | random_line_split |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
impl<I: Iterator<Item=char>> Iterator for Decompositions<I> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<char> {
while self.ready == 0 &&!self.done {
match (self.iter.next(), &self.kind) {
(Some(ch), &DecompositionType::Canonical) => {
... | {
if self.ready == 0 {
None
} else {
self.ready -= 1;
Some(self.buffer.remove(0).1)
}
} | identifier_body |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | ,
(None, _) => {
self.sort_pending();
self.done = true;
},
}
}
self.pop_front()
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (lower, _) = self.iter.size_hint();
(lower, None)
}
}
im... | {
super::char::decompose_compatible(ch, |d| self.push_back(d));
} | conditional_block |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#[inline]
fn next(&mut self) -> Option<char> {
while self.ready == 0 &&!self.done {
match (self.iter.next(), &self.kind) {
(Some(ch), &DecompositionType::Canonical) => {
super::char::decompose_canonical(ch, |d| self.push_back(d));
},
... | type Item = char; | random_line_split |
decompose.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
for c in self.clone() {
f.write_char(c)?;
}
Ok(())
}
}
| fmt | identifier_name |
scrobctl.rs | #![deny(
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, temp disable
clippy::all,
clippy::pedantic,
clippy::cargo,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unused_import_braces,
unused_qualifications,
unused_extern_crates,
varia... | () {
let _args = get_arguments();
unimplemented!();
}
| main | identifier_name |
scrobctl.rs | #![deny(
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, temp disable
clippy::all,
clippy::pedantic, | unused_qualifications,
unused_extern_crates,
variant_size_differences
)]
use clap::{App, Arg, ArgMatches};
fn get_arguments() -> ArgMatches<'static> {
App::new("scrobc")
.version(env!("CARGO_PKG_VERSION"))
.author("Dom Rodriguez <shymega@shymega.org.uk>")
.about("Client for contro... | clippy::cargo,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unused_import_braces, | random_line_split |
scrobctl.rs | #![deny(
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, temp disable
clippy::all,
clippy::pedantic,
clippy::cargo,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unused_import_braces,
unused_qualifications,
unused_extern_crates,
varia... | {
let _args = get_arguments();
unimplemented!();
} | identifier_body | |
client.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... |
/// Returns `true` if response status code is successful.
pub fn is_success(&self) -> bool {
self.status() == reqwest::StatusCode::Ok
}
/// Returns `true` if content type of this response is `text/html`
pub fn is_html(&self) -> bool {
match self.content_type() {
Some(Mime(mime::TopLevel::Text, mime::SubL... | {
match self.inner {
ResponseInner::Response(ref r) => *r.status(),
ResponseInner::NotFound => reqwest::StatusCode::NotFound,
_ => reqwest::StatusCode::Ok,
}
} | identifier_body |
client.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... | }
let res = match self.inner {
ResponseInner::Response(ref mut response) => response.read(buf),
ResponseInner::NotFound => return Ok(0),
ResponseInner::Reader(ref mut reader) => reader.read(buf),
};
// increase bytes read
if let Ok(read) = res {
self.read += read;
}
// check limit
match s... | random_line_split | |
client.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... | (self) where Self: Sized {}
}
const CLIENT_TIMEOUT_SECONDS: u64 = 5;
/// Fetch client
pub struct Client {
client: RwLock<(time::Instant, Arc<reqwest::Client>)>,
pool: CpuPool,
limit: Option<usize>,
}
impl Clone for Client {
fn clone(&self) -> Self {
let (ref time, ref client) = *self.client.read();
Client {
... | close | identifier_name |
defs.rs | //-
// Copyright (c) 2016, 2017, Jason Lingle
//
// This file is part of Ensync.
//
// Ensync is free software: you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any la... | (&self, other: &Self) -> bool {
match (self, other) {
(
&FileData::Regular(_, _, tself, _),
&FileData::Regular(_, _, tother, _),
) => tself > tother,
_ => false,
}
}
/// Returns whether this file object and another one represen... | newer_than | identifier_name |
defs.rs | //-
// Copyright (c) 2016, 2017, Jason Lingle
//
// This file is part of Ensync.
//
// Ensync is free software: you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any la... | use std::ffi::{OsStr, OsString};
use std::fmt;
/// Type for content hashes of regular files and for blob identifiers on the
/// server.
///
/// In practise, this is a 256-bit SHA-3 sum.
pub type HashId = [u8; 32];
/// The sentinal hash value indicating an uncomputed hash.
///
/// One does not compare hashes against th... | //
// You should have received a copy of the GNU General Public License along with
// Ensync. If not, see <http://www.gnu.org/licenses/>.
| random_line_split |
get_backup_keys.rs | //! `GET /_matrix/client/*/room_keys/keys`
//!
//! Retrieve all keys from a backup version.
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3room_keyskeys
use std::collections::BTreeMap;
use ruma_common::{api::ruma_api, RoomId};
... | (rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>) -> Self {
Self { rooms }
}
}
}
| new | identifier_name |
get_backup_keys.rs | //! `GET /_matrix/client/*/room_keys/keys`
//!
//! Retrieve all keys from a backup version.
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3room_keyskeys
use std::collections::BTreeMap;
use ruma_common::{api::ruma_api, RoomId};
... | #[ruma_api(query)]
pub version: &'a str,
}
response: {
/// A map from room IDs to session IDs to key data.
pub rooms: BTreeMap<Box<RoomId>, RoomKeyBackup>,
}
error: crate::Error
}
impl<'a> Request<'a> {
/// Creates a new ... | random_line_split | |
get_backup_keys.rs | //! `GET /_matrix/client/*/room_keys/keys`
//!
//! Retrieve all keys from a backup version.
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3room_keyskeys
use std::collections::BTreeMap;
use ruma_common::{api::ruma_api, RoomId};
... |
}
}
| {
Self { rooms }
} | identifier_body |
json_parser.rs | // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains bindings to convert from JSON to C++ base::Value objects.
// The code related to `base::Value` can be found in 'values.rs'
// and 'v... |
Ok(_) => true,
}
}
| {
*error_line = err.line().try_into().unwrap_or(-1);
*error_column = err.column().try_into().unwrap_or(-1);
error_message.as_mut().clear();
// The following line pulls in a lot of binary bloat, due to all the formatter
// implementations required to stringify ... | conditional_block |
json_parser.rs | // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains bindings to convert from JSON to C++ base::Value objects.
// The code related to `base::Value` can be found in 'values.rs'
// and 'v... | } | random_line_split | |
json_parser.rs | // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains bindings to convert from JSON to C++ base::Value objects.
// The code related to `base::Value` can be found in 'values.rs'
// and 'v... | (
json: &[u8],
options: JsonOptions,
value_slot: ValueSlotRef,
) -> Result<(), serde_jsonrc::Error> {
let mut to_parse = json;
if to_parse.len() >= 3 && to_parse[0..3] == UTF8_BOM {
to_parse = &to_parse[3..];
}
let mut deserializer = serde_jsonrc::Deserializer::new(SliceRead::new(
... | decode_json | identifier_name |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... | <T: Copy>(pool: &[T], reservoir_size: usize) -> Vec<T> {
assert!(pool.len() >= reservoir_size,
"Sample size is greater than total.");
let mut pool_mut = &pool[..];
let mut res = pool_mut[..reservoir_size].to_vec();
pool_mut = &pool_mut[reservoir_size..];
let mut ele_seen = reservoir_s... | reservoir_sample | identifier_name |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... | let a = (0..10).collect::<Vec<_>>();
let b = fisher_yates(&a);
for val in a.iter() {
assert!(b.contains(val));
}
}
#[test]
fn test_in_place_fisher_yates() {
let mut a = (0..10).collect::<Vec<_>>();
in_place_fisher_yates(&mut a);
for va... | #[test]
fn test_fisher_yates() { | random_line_split |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... |
}
res
}
/// The inside out Fisher-Yates algorithm.
///
/// # Examples
///
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// // Collect the numbers 0..5
/// let a = (0..5).collect::<Vec<_>>();
///
/// // Perform a Fisher-Yates shuffle to get a random permutation
/// let permutation = rand_... | {
res[r] = p_0;
} | conditional_block |
rand_utils.rs | //! Utility functions for random functionality.
//!
//! This module provides sampling and shuffling which are used
//! within the learning modules.
use rand::{Rng, thread_rng};
/// ```
/// use rusty_machine::learning::toolkit::rand_utils;
///
/// let mut pool = &mut [1,2,3,4];
/// let sample = rand_utils::reservoir_s... |
}
| {
let mut a = (0..10).collect::<Vec<_>>();
in_place_fisher_yates(&mut a);
for val in 0..10 {
assert!(a.contains(&val));
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.