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 |
|---|---|---|---|---|
getat_func.rs | //! # getat_func
//!
//! Split function which returns only the requested item from the created array.
//!
#[cfg(test)]
#[path = "getat_func_test.rs"]
mod getat_func_test;
use envmnt;
pub(crate) fn | (function_args: &Vec<String>) -> Vec<String> {
if function_args.len()!= 3 {
error!(
"split expects only 3 arguments (environment variable name, split by character, index)"
);
}
let env_key = function_args[0].clone();
let split_by = function_args[1].clone();
let index: us... | invoke | identifier_name |
timer.rs | // TODO: How can we test this module?
use std::cell::{RefCell, Cell};
use std::fmt;
use std::rc::Rc;
use cpu::irq::{self, IrqClient};
use io::regs::IoReg;
#[derive(Clone, Copy, Debug)]
pub enum Prescaler {
Div1 = 0,
Div64 = 1,
Div256 = 2,
Div1024 = 3,
}
impl Prescaler {
fn new(val: u16) -> Presc... | }
}
/// Returns the number of CPU clocks until this timer triggers an overflow
fn clocks_till_overflow(&self) -> u64 {
match self.val_cycles {
Cycles::Unscaled(cyc) => {
let period = unscale(1 << 16, self.prescaler);
(period - cyc % period)
... | out
} else { unreachable!() }
} | random_line_split |
timer.rs | // TODO: How can we test this module?
use std::cell::{RefCell, Cell};
use std::fmt;
use std::rc::Rc;
use cpu::irq::{self, IrqClient};
use io::regs::IoReg;
#[derive(Clone, Copy, Debug)]
pub enum Prescaler {
Div1 = 0,
Div64 = 1,
Div256 = 2,
Div1024 = 3,
}
impl Prescaler {
fn new(val: u16) -> Presc... | else {
let ctr = timer_states.global_counter.get();
let baseline = timer_states.start_counters[index].get();
let clock_diff = ctr - baseline;
timer_states.start_counters[index].set(ctr);
Cycles::Unscaled(clock_diff)
};
prev_overflowed = time... | {
Cycles::CountUp(prev_overflowed as u64)
} | conditional_block |
timer.rs | // TODO: How can we test this module?
use std::cell::{RefCell, Cell};
use std::fmt;
use std::rc::Rc;
use cpu::irq::{self, IrqClient};
use io::regs::IoReg;
#[derive(Clone, Copy, Debug)]
pub enum Prescaler {
Div1 = 0,
Div64 = 1,
Div256 = 2,
Div1024 = 3,
}
impl Prescaler {
fn | (val: u16) -> Prescaler {
match val {
0 => Prescaler::Div1,
1 => Prescaler::Div64,
2 => Prescaler::Div256,
3 => Prescaler::Div1024,
_ => unreachable!()
}
}
}
bf!(CntReg[u16] {
prescaler: 0:1,
count_up: 2:2,
irq_enable: 6:6,
... | new | identifier_name |
issue-44197.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (_: &str) -> Result<String, ()> {
Err(())
}
fn bar2(baz: String) -> impl Generator<Yield = String, Return = ()> {
move || {
if let Ok(quux) = foo2(&baz) {
yield quux;
}
}
}
fn main() {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::... | foo2 | identifier_name |
issue-44197.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
fn main() {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::new()));
assert_eq!(bar2(String::new()).resume(), GeneratorState::Complete(()));
}
}
| {
yield quux;
} | conditional_block |
issue-44197.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn bar2(baz: String) -> impl Generator<Yield = String, Return = ()> {
move || {
if let Ok(quux) = foo2(&baz) {
yield quux;
}
}
}
fn main() {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::new()));
assert_eq!(bar2(String::new()... | fn foo2(_: &str) -> Result<String, ()> {
Err(()) | random_line_split |
issue-44197.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
unsafe {
assert_eq!(bar(String::new()).resume(), GeneratorState::Yielded(String::new()));
assert_eq!(bar2(String::new()).resume(), GeneratorState::Complete(()));
}
} | identifier_body | |
exception.rs | use crate::wrapper::{NIF_ENV, NIF_TERM};
/// Raise an "error exception".
///
/// # Unsafe
///
/// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// ... | /// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// And of course `env` must be a valid environment.
pub unsafe fn raise_badarg(env: NIF_ENV) -> NI... | random_line_split | |
exception.rs | use crate::wrapper::{NIF_ENV, NIF_TERM};
/// Raise an "error exception".
///
/// # Unsafe
///
/// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// ... | (env: NIF_ENV) -> NIF_TERM {
rustler_sys::enif_make_badarg(env)
}
| raise_badarg | identifier_name |
exception.rs | use crate::wrapper::{NIF_ENV, NIF_TERM};
/// Raise an "error exception".
///
/// # Unsafe
///
/// The value returned by this function "can be used only as the return value
/// from the NIF that invoked it (directly or indirectly) or be passed to
/// `enif_is_exception`, but not to any other NIF API function."
///
/// ... | {
rustler_sys::enif_make_badarg(env)
} | identifier_body | |
action.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 std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... | .spawn()?; // do not retry if failed to start
info!(
"{} Fire `hg cloud sync` attempt {}, spawned process id '{}'",
sid,
i,
child.id()
);
let output = child.wait_with_output()?;
info!(
... | {
let mut workspace_args = vec!["--raw-workspace-name".to_owned(), workspace];
if let Some(version) = version {
workspace_args.append(&mut vec![
"--workspace-version".to_owned(),
version.to_string(),
]);
}
for i in 0..retries {
... | identifier_body |
action.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 std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... |
} else {
info!("{} Cloud Sync was successful", sid);
return Ok(());
}
}
Ok(())
}
}
| {
return Err(ErrorKind::CommitCloudHgCloudSyncError(format!(
"process exited with: {}, retry later",
output.status
))
.into());
} | conditional_block |
action.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 std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... |
let output = child.wait_with_output()?;
info!(
"{} stdout: \n{}",
sid,
String::from_utf8_lossy(&output.stdout).trim()
);
info!(
"{} stderr: \n{}",
sid,
String::from_utf8_loss... | "{} Fire `hg cloud sync` attempt {}, spawned process id '{}'",
sid,
i,
child.id()
); | random_line_split |
action.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 std::path::Path;
use std::process::Command;
use std::process::Stdio;
use std::time::Instant;
use anyhow::Result;
use log::error;
use l... | <P: AsRef<Path>>(
sid: &String,
path: P,
retries: u32,
version: Option<u64>,
workspace: String,
reason: String,
) -> Result<()> {
let mut workspace_args = vec!["--raw-workspace-name".to_owned(), workspace];
if let Some(version) = version {
... | fire | identifier_name |
hash.rs | // Copyright 2015, 2016 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 la... |
assert_eq!(H128::from(0x1234567890abcdef), H128::from_str("00000000000000001234567890abcdef").unwrap());
assert_eq!(H64::from(0x1234567890abcdef), H64::from_str("1234567890abcdef").unwrap());
assert_eq!(H32::from(0x1234567890abcdef), H32::from_str("90abcdef").unwrap());
}
#[test]
fn from_str() {
assert_eq!... | _u64() { | identifier_name |
hash.rs | // Copyright 2015, 2016 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 la... | impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
known_heap_size!(0, H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048);
// Specialized HashMap and HashSet
/// Hasher that just takes 8 bytes of the provided value.
/// May only be used for keys which are 32 bytes.
pu... | impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33); | random_line_split |
hash.rs | // Copyright 2015, 2016 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 la... |
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&valu... | let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
} | identifier_body |
hash.rs | // Copyright 2015, 2016 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 la... |
}
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $... | {
s
} | conditional_block |
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.
*/
//! An async-compatible HTTP client built on top of libcurl.
#![allow(dead_code)]
mod client;
mod driver;
mod errors;
mod event_listeners;
m... | /* | random_line_split | |
echo-udp.rs | //! An UDP echo server that just sends back everything that it receives.
//!
//! If you're on unix you can test this out by in one terminal executing:
//!
//! cargo run --example echo-udp
//!
//! and in another terminal you can run:
//!
//! cargo run --example connect -- --udp 127.0.0.1:8080
//!
//! Each line y... |
// If we're here then `to_send` is `None`, so we take a look for the
// next message we're going to echo back.
self.to_send = Some(try_nb!(self.socket.recv_from(&mut self.buf)));
}
}
}
fn main() {
let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()... | {
let amt = try_nb!(self.socket.send_to(&self.buf[..size], &peer));
println!("Echoed {}/{} bytes to {}", amt, size, peer);
self.to_send = None;
} | conditional_block |
echo-udp.rs | //! An UDP echo server that just sends back everything that it receives.
//!
//! If you're on unix you can test this out by in one terminal executing:
//!
//! cargo run --example echo-udp
//!
//! and in another terminal you can run:
//!
//! cargo run --example connect -- --udp 127.0.0.1:8080
//!
//! Each line y... | (&mut self) -> Poll<(), io::Error> {
loop {
// First we check to see if there's a message we need to echo back.
// If so then we try to send it back to the original source, waiting
// until it's writable and we're able to do so.
if let Some((size, peer)) = self.to... | poll | identifier_name |
echo-udp.rs | //! An UDP echo server that just sends back everything that it receives. | //! cargo run --example echo-udp
//!
//! and in another terminal you can run:
//!
//! cargo run --example connect -- --udp 127.0.0.1:8080
//!
//! Each line you type in to the `nc` terminal should be echo'd back to you!
extern crate futures;
#[macro_use]
extern crate tokio;
#[macro_use]
extern crate tokio_io;
... | //!
//! If you're on unix you can test this out by in one terminal executing:
//! | random_line_split |
list_issues.rs | extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
use gitlab::GitLab;
// use gitlab::Pagination;
use gitlab::issues;
use gitlab::Lister;
use gitlab::errors::*;
fn main() {
if let Err(ref e) = run() {
println!("error: {}", e);
for e in e.it... | }
};
let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?;
// let gl = GitLab::new(&hostname, &token)
// .chain_err(|| "failure to create GitLab instance")?
// .scheme("http").port(80);
// let gl = gl.scheme("http").port(80);
let issues =... | {
env_logger::init().unwrap();
info!("starting up");
let hostname = match env::var("GITLAB_HOSTNAME") {
Ok(val) => val,
Err(_) => {
let default = String::from("gitlab.com");
println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
... | identifier_body |
list_issues.rs | extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
use gitlab::GitLab;
// use gitlab::Pagination;
use gitlab::issues;
use gitlab::Lister;
use gitlab::errors::*;
fn | () {
if let Err(ref e) = run() {
println!("error: {}", e);
for e in e.iter().skip(1) {
println!("caused by: {}", e);
}
// The backtrace is not always generated. Try to run this example
// with `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
... | main | identifier_name |
list_issues.rs | extern crate gitlab_api as gitlab;
use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
use gitlab::GitLab;
// use gitlab::Pagination;
use gitlab::issues;
use gitlab::Lister;
use gitlab::errors::*;
fn main() {
if let Err(ref e) = run() {
println!("error: {}", e);
for e in e.it... | let hostname = match env::var("GITLAB_HOSTNAME") {
Ok(val) => val,
Err(_) => {
let default = String::from("gitlab.com");
println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
default);
default
}
};
... | info!("starting up");
| random_line_split |
table.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/. */
//! CSS table formatting contexts.
use layout::box_::Box;
use layout::block::BlockFlow;
use layout::block::{Width... |
TableFlow {
block_flow: block_flow,
col_widths: ~[],
table_layout: table_layout
}
}
pub fn teardown(&mut self) {
self.block_flow.teardown();
self.col_widths = ~[];
}
/// Assign height for table flow.
///
/// inline(always) be... |
AutoLayout
}; | conditional_block |
table.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/. */
//! CSS table formatting contexts.
use layout::box_::Box;
use layout::block::BlockFlow;
use layout::block::{Width... |
pub fn teardown(&mut self) {
self.block_flow.teardown();
self.col_widths = ~[];
}
/// Assign height for table flow.
///
/// inline(always) because this is only ever called by in-order or non-in-order top-level
/// methods
#[inline(always)]
fn assign_height_table_base(&m... |
let mut block_flow = BlockFlow::float_from_node(constructor, node, float_kind);
let table_layout = if block_flow.box_().style().Table.get().table_layout ==
table_layout::fixed {
FixedLayout
} else {
AutoLayout
};
TableFlow {
... | identifier_body |
table.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/. */
//! CSS table formatting contexts.
use layout::box_::Box;
use layout::block::BlockFlow;
use layout::block::{Width... | constructor: &mut FlowConstructor,
node: &ThreadSafeLayoutNode,
float_kind: FloatKind)
-> TableFlow {
let mut block_flow = BlockFlow::float_from_node(constructor, node, float_kind);
let table_layout = if block_flow.box_().s... | loat_from_node( | identifier_name |
table.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/. */
//! CSS table formatting contexts.
use layout::box_::Box;
use layout::block::BlockFlow;
use layout::block::{Width... | /// Column widths
col_widths: ~[Au],
/// Table-layout property
table_layout: TableLayout,
}
impl TableFlow {
pub fn from_node_and_box(node: &ThreadSafeLayoutNode,
box_: Box)
-> TableFlow {
let mut block_flow = BlockFlow::from_node_a... | random_line_split | |
instance.rs | use std::io::{self, BufRead, BufReader, ErrorKind, Result};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::Duration;
use avro_rs::{from_value, Reader, Schema, Wri... | {
request: Request,
response: Option<Response>,
}
#[derive(Debug)]
struct InstanceContext {
stream: TcpStream,
receiver: Receiver<Arc<InstanceMessage>>,
}
impl Instance {
pub fn new(config: InstanceConfig) -> Result<Instance> {
let mut child = Command::new(&config.command)
.std... | InstanceMessage | identifier_name |
instance.rs | use std::io::{self, BufRead, BufReader, ErrorKind, Result};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
use std::sync::Arc;
use std::thread::{self, JoinHandle}; | use super::config::InstanceConfig;
use super::request::Request;
use super::response::Response;
fn initial_connect(child: &mut Child) -> Result<TcpStream> {
let child_stdout = child
.stdout
.as_mut()
.expect("Failed to retrieve child stdout");
let mut reader = BufReader::new(child_stdout);... | use std::time::Duration;
use avro_rs::{from_value, Reader, Schema, Writer};
| random_line_split |
rc.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | impl<T: Ord> Ord for Rc<T> {
#[inline]
fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
}
impl<T: fmt::Show> fmt::Show for Rc<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
/// Weak reference to a reference-counted box
#[unsafe_no_drop_flag]
... | #[inline(always)]
fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
}
| random_line_split |
rc.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
}
}
}
#[unstable]
impl<T> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
self.inc_weak();
Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoShare }
}
}
#[doc(hidden)]
trait RcBoxPtr<T> {
fn inner<'a>(&'a self) -> &'a RcBox<T>;
... | {
deallocate(self._ptr as *mut u8, size_of::<RcBox<T>>(),
min_align_of::<RcBox<T>>())
} | conditional_block |
rc.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self) -> Rc<T> {
self.inc_strong();
Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoShare }
}
}
impl<T: Default> Default for Rc<T> {
#[inline]
fn default() -> Rc<T> {
Rc::new(Default::default())
}
}
impl<T: PartialEq> PartialEq for Rc<T> {
#[inline(alwa... | clone | identifier_name |
rc.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#[test]
fn weak_self_cyclic() {
struct Cycle {
x: RefCell<Option<Weak<Cycle>>>
}
let a = Rc::new(Cycle { x: RefCell::new(None) });
let b = a.clone().downgrade();
*a.x.borrow_mut() = Some(b);
// hopefully we don't double-free (or leak)...
}
... | {
// see issue #11532
use std::gc::GC;
let a = Rc::new(RefCell::new(box(GC) 1i));
assert!(a.try_borrow_mut().is_some());
} | identifier_body |
main.rs | /// Returns true if the string is a palindrome
fn | (string: &str) -> bool {
// The first part of the string
let forward = string.chars().take(string.len() / 2);
// The second part of the string in reverse order
let reverse = string.chars().rev().take(string.len() / 2);
// We group the two parts of the string in tuples
let mut both_directions =... | palindrome | identifier_name |
main.rs | /// Returns true if the string is a palindrome
fn palindrome(string: &str) -> bool {
// The first part of the string
let forward = string.chars().take(string.len() / 2);
// The second part of the string in reverse order
let reverse = string.chars().rev().take(string.len() / 2);
// We group the two... |
#[test]
fn test_palindromes() {
let palindromes = ["eevee", "lalalal", "オオオオ", "", "anna"];
let non_palindromes = ["nope", "lalala", "car", "rain", "house", "computer", "rust"];
assert!(palindromes.iter().all(|&s| palindrome(s)));
assert!(non_palindromes.iter().all(|&s|!palindrome(s)));
}
| {
let test_strings = ["nope", "eevee", "lalala", "rust", "lalalal"];
for &string in &test_strings {
println!("{}: {}", string, palindrome(string));
}
} | identifier_body |
main.rs | /// Returns true if the string is a palindrome
fn palindrome(string: &str) -> bool {
// The first part of the string
let forward = string.chars().take(string.len() / 2);
// The second part of the string in reverse order
let reverse = string.chars().rev().take(string.len() / 2);
// We group the two... | } | let palindromes = ["eevee", "lalalal", "オオオオ", "", "anna"];
let non_palindromes = ["nope", "lalala", "car", "rain", "house", "computer", "rust"];
assert!(palindromes.iter().all(|&s| palindrome(s)));
assert!(non_palindromes.iter().all(|&s| !palindrome(s))); | random_line_split |
lib.rs | #![feature(pub_restricted, slice_patterns)]
#[macro_use]
extern crate gfx;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate rusttype;
extern crate conrod;
extern crate cgmath;
extern crate image;
extern crate quickersort;
extern crate rayon;
pub mod ... | (&mut self, bind: TextureBind, color: TextureView<ColorFormat>) {
self.texture_binds.get_mut(bind).color = color;
}
pub fn update_bound_normal(&mut self, bind: TextureBind, normal: TextureView<NormalFormat>) {
self.texture_binds.get_mut(bind).normal = normal;
}
pub fn unbind_textures(&... | update_bound_color | identifier_name |
lib.rs | #![feature(pub_restricted, slice_patterns)]
#[macro_use]
extern crate gfx;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate rusttype;
extern crate conrod;
extern crate cgmath;
extern crate image;
extern crate quickersort;
extern crate rayon;
pub mod ... | should_flush: false,
}
}
pub fn clear(&mut self, color: NormalizedColor) {
self.graphics.encoder.clear(&self.graphics.output_color, color.to_array());
self.should_flush();
}
pub fn should_flush(&mut self) {
self.should_flush = true;
}
pub fn flush(&... | fn new(graphics: &'a mut Graphics) -> Self {
Frame {
graphics: graphics, | random_line_split |
lib.rs | #![feature(pub_restricted, slice_patterns)]
#[macro_use]
extern crate gfx;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate rusttype;
extern crate conrod;
extern crate cgmath;
extern crate image;
extern crate quickersort;
extern crate rayon;
pub mod ... |
pub fn flush(&mut self) {
self.graphics.encoder.flush(&mut self.graphics.device);
self.should_flush = false;
}
pub fn ensure_flushed(&mut self) {
if self.should_flush { self.flush(); }
}
pub fn present(mut self, window: &'a Window) {
use gfx::traits::*;
s... | {
self.should_flush = true;
} | identifier_body |
lib.rs | #![feature(pub_restricted, slice_patterns)]
#[macro_use]
extern crate gfx;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate rusttype;
extern crate conrod;
extern crate cgmath;
extern crate image;
extern crate quickersort;
extern crate rayon;
pub mod ... |
}
pub fn present(mut self, window: &'a Window) {
use gfx::traits::*;
self.ensure_flushed();
window.swap_buffers().unwrap();
self.graphics.device.cleanup();
}
}
| { self.flush(); } | conditional_block |
main.rs | // Copyright 2019 Yin Guanhao <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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... | Ok(())
}
| {
let dirs = ["src", "benches"];
let mut has_error = false;
for entry in dirs.iter().map(WalkDir::new).flatten() {
let entry = entry?;
if entry.file_type().is_file() && entry.path().extension() == Some(OsStr::new("rs")) {
let file_content = std::fs::read_to_string(entry.path())
... | identifier_body |
main.rs | // Copyright 2019 Yin Guanhao <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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... | () -> anyhow::Result<()> {
let dirs = ["src", "benches"];
let mut has_error = false;
for entry in dirs.iter().map(WalkDir::new).flatten() {
let entry = entry?;
if entry.file_type().is_file() && entry.path().extension() == Some(OsStr::new("rs")) {
let file_content = std::fs::read_... | main | identifier_name |
main.rs | // Copyright 2019 Yin Guanhao <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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... | entry.path().display()
);
has_error = true;
}
}
}
if has_error {
bail!("Error occurred");
}
Ok(())
} | if !file_content.starts_with("// Copyright") {
eprintln!(
"Missing copyright claim in file: {}", | random_line_split |
main.rs | // Copyright 2019 Yin Guanhao <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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... |
}
}
if has_error {
bail!("Error occurred");
}
Ok(())
}
| {
eprintln!(
"Missing copyright claim in file: {}",
entry.path().display()
);
has_error = true;
} | conditional_block |
framerate.rs | //! Framerate control
use libc;
use libc::{c_void, uint32_t, size_t};
use std::mem;
use sdl2::get_error;
mod ll {
/* automatically generated by rust-bindgen */
use libc::*;
#[repr(C)]
pub struct FPSmanager {
pub framecount: uint32_t,
pub rateticks: c_float,
pub baseticks: uin... | unsafe {
let size = mem::size_of::<ll::FPSmanager>() as size_t;
let raw = libc::malloc(size) as *mut ll::FPSmanager;
ll::SDL_initFramerate(raw);
FPSManager { raw: raw }
}
}
/// Set the framerate in Hz.
pub fn set_framerate(&mut self, rate: u32... | }
impl FPSManager {
/// Create the framerate manager.
pub fn new() -> FPSManager { | random_line_split |
framerate.rs | //! Framerate control
use libc;
use libc::{c_void, uint32_t, size_t};
use std::mem;
use sdl2::get_error;
mod ll {
/* automatically generated by rust-bindgen */
use libc::*;
#[repr(C)]
pub struct FPSmanager {
pub framecount: uint32_t,
pub rateticks: c_float,
pub baseticks: uin... | (&mut self) -> u32 {
unsafe { ll::SDL_framerateDelay(self.raw) as u32 }
}
}
impl Drop for FPSManager {
fn drop(&mut self) {
unsafe { libc::free(self.raw as *mut c_void) }
}
}
| delay | identifier_name |
framerate.rs | //! Framerate control
use libc;
use libc::{c_void, uint32_t, size_t};
use std::mem;
use sdl2::get_error;
mod ll {
/* automatically generated by rust-bindgen */
use libc::*;
#[repr(C)]
pub struct FPSmanager {
pub framecount: uint32_t,
pub rateticks: c_float,
pub baseticks: uin... |
/// Delay execution to maintain a constant framerate and calculate fps.
pub fn delay(&mut self) -> u32 {
unsafe { ll::SDL_framerateDelay(self.raw) as u32 }
}
}
impl Drop for FPSManager {
fn drop(&mut self) {
unsafe { libc::free(self.raw as *mut c_void) }
}
}
| {
// will not get an error
unsafe { ll::SDL_getFramecount(self.raw) as i32 }
} | identifier_body |
main.rs | ::BlobRepo;
use bookmarks::{BookmarkName, Freshness};
use cached_config::ConfigStore;
use clap_old::ArgMatches;
use cmdlib::{
args::{self, MononokeClapApp, MononokeMatches},
helpers, monitoring,
};
use cmdlib_x_repo::create_commit_syncer_from_matches;
use context::CoreContext;
use cross_repo_sync::{
types::... |
if!skip {
let (stats, res) = sync_single_bookmark_update_log(
&ctx,
&commit_syncer,
entry,
source_skiplist_index,
target_skiplist_index,
&common_pushrebase_bookmarks,
... | {
if !regex.is_match(entry.bookmark_name.as_str()) {
skip = true;
}
} | conditional_block |
main.rs | epo::BlobRepo;
use bookmarks::{BookmarkName, Freshness};
use cached_config::ConfigStore;
use clap_old::ArgMatches;
use cmdlib::{
args::{self, MononokeClapApp, MononokeMatches},
helpers, monitoring,
};
use cmdlib_x_repo::create_commit_syncer_from_matches;
use context::CoreContext;
use cross_repo_sync::{
type... | commit_syncer,
scuba_sample,
source_skiplist_index,
target_skiplist_index,
maybe_target_bookmark,
common_bookmarks,
)
.await
}
(ARG_TAIL, Some(sub_m)) => {
add_common_fields... | random_line_split | |
main.rs | ::BlobRepo;
use bookmarks::{BookmarkName, Freshness};
use cached_config::ConfigStore;
use clap_old::ArgMatches;
use cmdlib::{
args::{self, MononokeClapApp, MononokeMatches},
helpers, monitoring,
};
use cmdlib_x_repo::create_commit_syncer_from_matches;
use context::CoreContext;
use cross_repo_sync::{
types::... | <
M: SyncedCommitMapping + Clone +'static,
C: MutableCounters + Clone + Sync +'static,
>(
ctx: &CoreContext,
commit_syncer: &CommitSyncer<M>,
mutable_counters: &C,
mut scuba_sample: MononokeScubaSampleBuilder,
common_pushrebase_bookmarks: &HashSet<BookmarkName>,
source_skiplist_index: &S... | tail | identifier_name |
main.rs |
use futures::{
compat::Future01CompatExt,
future::{self, try_join},
stream::{self, TryStreamExt},
StreamExt,
};
use futures_stats::TimedFutureExt;
use live_commit_sync_config::{CfgrLiveCommitSyncConfig, LiveCommitSyncConfig};
use mononoke_api_types::InnerRepo;
use mononoke_hg_sync_job_helper_lib::wait_... | {
let matches = app.get_matches(fb)?;
let logger = matches.logger();
let ctx = CoreContext::new_with_logger(fb, logger.clone());
Ok((ctx, matches))
} | identifier_body | |
2_6_attraction.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 2-6: Attraction
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
mover: Mover,
attractor: Attractor,
}
struct Mover {
position: Point2,
velocity: Vector2,
acceleratio... |
}
fn stop_dragging(&mut self) {
self.dragging = false;
}
fn drag(&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my + self.drag_offset.y;
}
}
}
impl Mover {
fn new() -> Self {
... | {
self.roll_over = false;
} | conditional_block |
2_6_attraction.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 2-6: Attraction
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
mover: Mover,
attractor: Attractor,
}
struct Mover {
position: Point2,
velocity: Vector2,
acceleratio... |
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
} | let draw = app.draw();
draw.background().color(WHITE);
m.attractor.display(&draw);
m.mover.display(&draw); | random_line_split |
2_6_attraction.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 2-6: Attraction
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
mover: Mover,
attractor: Attractor,
}
struct Mover {
position: Point2,
velocity: Vector2,
acceleratio... | (&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my + self.drag_offset.y;
}
}
}
impl Mover {
fn new() -> Self {
let position = pt2(80.0, 130.0);
let velocity = vec2(1.0, 0.0);
let acce... | drag | identifier_name |
elided-lifetime.rs | // aux-build:elided-lifetime.rs
//
// rust-lang/rust#75225
//
// Since Rust 2018 we encourage writing out <'_> explicitly to make it clear
// that borrowing is occuring. Make sure rustdoc is following the same idiom. | pub struct Ref<'a>(&'a u32);
type ARef<'a> = Ref<'a>;
// @has foo/fn.test1.html
// @matches - "Ref</a><'_>"
pub fn test1(a: &u32) -> Ref {
Ref(a)
}
// @has foo/fn.test2.html
// @matches - "Ref</a><'_>"
pub fn test2(a: &u32) -> Ref<'_> {
Ref(a)
}
// @has foo/fn.test3.html
// @matches - "Ref</a><... |
#![crate_name = "foo"]
| random_line_split |
elided-lifetime.rs | // aux-build:elided-lifetime.rs
//
// rust-lang/rust#75225
//
// Since Rust 2018 we encourage writing out <'_> explicitly to make it clear
// that borrowing is occuring. Make sure rustdoc is following the same idiom.
#![crate_name = "foo"]
pub struct Ref<'a>(&'a u32);
type ARef<'a> = Ref<'a>;
// @has foo/fn.test1.ht... | (a: &u32) -> ARef<'_> {
Ref(a)
}
// Ensure external paths in inlined docs also display elided lifetime
// @has foo/bar/fn.test5.html
// @matches - "Ref</a><'_>"
// @has foo/bar/fn.test6.html
// @matches - "Ref</a><'_>"
#[doc(inline)]
pub extern crate bar;
| test4 | identifier_name |
compositor_task.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/. */
//! Communication with the compositor task.
use CompositorMsg as ConstellationMsg;
use compositor;
use euclid::po... | self.send(Msg::GetNativeDisplay(chan));
// If the compositor is shutting down when a paint task
// is being created, the compositor won't respond to
// this message, resulting in an eventual panic. Instead,
// just return None in this case, since the paint task
// will ex... | /// Implementation of the abstract `PaintListener` interface.
impl PaintListener for Box<CompositorProxy + 'static + Send> {
fn native_display(&mut self) -> Option<NativeDisplay> {
let (chan, port) = channel(); | random_line_split |
compositor_task.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/. */
//! Communication with the compositor task.
use CompositorMsg as ConstellationMsg;
use compositor;
use euclid::po... | {
/// A channel to the compositor.
pub sender: Box<CompositorProxy + Send>,
/// A port on which messages inbound to the compositor can be received.
pub receiver: Box<CompositorReceiver>,
/// A channel to the constellation.
pub constellation_chan: Sender<ConstellationMsg>,
/// A channel to t... | InitialCompositorState | identifier_name |
compositor_task.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/. */
//! Communication with the compositor task.
use CompositorMsg as ConstellationMsg;
use compositor;
use euclid::po... |
fn assign_painted_buffers(&mut self,
pipeline_id: PipelineId,
epoch: Epoch,
replies: Vec<(LayerId, Box<LayerBufferSet>)>,
frame_tree_id: FrameTreeId) {
self.send(Msg::AssignPaintedBuffer... | {
let (chan, port) = channel();
self.send(Msg::GetNativeDisplay(chan));
// If the compositor is shutting down when a paint task
// is being created, the compositor won't respond to
// this message, resulting in an eventual panic. Instead,
// just return None in this case,... | identifier_body |
sysinfo.rs | use libc::{self, SI_LOAD_SHIFT};
use std::{cmp, mem};
use std::time::Duration;
use Result;
use errno::Errno;
/// System info structure returned by `sysinfo`.
#[derive(Copy, Clone)]
#[allow(missing_debug_implementations)] // libc::sysinfo doesn't impl Debug
pub struct SysInfo(libc::sysinfo);
impl SysInfo {
/// Re... |
/// Current number of processes.
pub fn process_count(&self) -> u16 {
self.0.procs
}
/// Returns the amount of swap memory in Bytes.
pub fn swap_total(&self) -> u64 {
self.scale_mem(self.0.totalswap)
}
/// Returns the amount of unused swap memory in Bytes.
pub fn swap_... | // Truncate negative values to 0
Duration::from_secs(cmp::max(self.0.uptime, 0) as u64)
} | random_line_split |
sysinfo.rs | use libc::{self, SI_LOAD_SHIFT};
use std::{cmp, mem};
use std::time::Duration;
use Result;
use errno::Errno;
/// System info structure returned by `sysinfo`.
#[derive(Copy, Clone)]
#[allow(missing_debug_implementations)] // libc::sysinfo doesn't impl Debug
pub struct SysInfo(libc::sysinfo);
impl SysInfo {
/// Re... | (&self) -> u64 {
self.scale_mem(self.0.totalram)
}
/// Returns the amount of completely unused RAM in Bytes.
///
/// "Unused" in this context means that the RAM in neither actively used by
/// programs, nor by the operating system as disk cache or buffer. It is
/// "wasted" RAM since it... | ram_total | identifier_name |
edge_outside.rs | use crate::mock_graph::{
arbitrary::{GuidedArbGraph, Limit, VertexOutside},
MockVertex, TestGraph,
};
use graphene::{
core::{Ensure, Graph},
impl_ensurer,
};
use quickcheck::{Arbitrary, Gen};
use std::collections::HashSet;
/// An arbitrary graph and two vertices where at least one is not in the graph.
#[derive(Clo... | <G>(pub G, pub MockVertex, pub MockVertex)
where
G: GuidedArbGraph,
G::Graph: TestGraph;
impl<G> Ensure for EdgeOutside<G>
where
G: GuidedArbGraph,
G::Graph: TestGraph,
{
fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self
{
unimplemented!()
}
fn validate(_c: &Self::Ensured, _: &()) -> bool
{
unimple... | EdgeOutside | identifier_name |
edge_outside.rs | use crate::mock_graph::{
arbitrary::{GuidedArbGraph, Limit, VertexOutside},
MockVertex, TestGraph,
};
use graphene::{
core::{Ensure, Graph},
impl_ensurer,
};
use quickcheck::{Arbitrary, Gen};
use std::collections::HashSet;
/// An arbitrary graph and two vertices where at least one is not in the graph.
#[derive(Clo... | where
G: GuidedArbGraph,
G::Graph: TestGraph,
{
fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self
{
unimplemented!()
}
fn validate(_c: &Self::Ensured, _: &()) -> bool
{
unimplemented!()
}
}
impl_ensurer! {
use<G> EdgeOutside<G>: Ensure
as (self.0): G
where
G: GuidedArbGraph,
G::Graph: TestGraph... | impl<G> Ensure for EdgeOutside<G> | random_line_split |
edge_outside.rs | use crate::mock_graph::{
arbitrary::{GuidedArbGraph, Limit, VertexOutside},
MockVertex, TestGraph,
};
use graphene::{
core::{Ensure, Graph},
impl_ensurer,
};
use quickcheck::{Arbitrary, Gen};
use std::collections::HashSet;
/// An arbitrary graph and two vertices where at least one is not in the graph.
#[derive(Clo... | .map(|v| Self(self.0.clone(), v, self.2)),
);
result.extend(
self.2
.shrink()
.filter(|v| {
!self.0.graph().contains_vertex(self.1) ||!self.0.graph().contains_vertex(v)
})
.map(|v| Self(self.0.clone(), self.1, v)),
);
Box::new(result.into_iter())
}
}
| {
let mut result = Vec::new();
// Shrink the graph, keeping only the shrunk graphs where the edge is still
// invalid.
result.extend(
self.0
.shrink_guided(limits.clone())
.filter(|g| {
!g.graph().contains_vertex(self.1) || !g.graph().contains_vertex(self.2)
})
.map(|g| Self(g, self.1, ... | identifier_body |
wrapping_square.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_wrapping_square() {
fn test<T: PrimitiveInt>(x: T, ou... | {
apply_fn_to_unsigneds!(wrapping_square_properties_helper_unsigned);
apply_fn_to_signeds!(wrapping_square_properties_helper_signed);
} | identifier_body | |
wrapping_square.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_wrapping_square() {
fn test<T: PrimitiveInt>(x: T, ou... | <T: PrimitiveUnsigned>() {
unsigned_gen::<T>().test_properties(|x| {
let mut square = x;
square.wrapping_square_assign();
assert_eq!(square, x.wrapping_square());
assert_eq!(square, x.wrapping_pow(2));
});
}
fn wrapping_square_properties_helper_signed<T: PrimitiveSigned>() {
... | wrapping_square_properties_helper_unsigned | identifier_name |
wrapping_square.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_wrapping_square() {
fn test<T: PrimitiveInt>(x: T, ou... |
});
}
#[test]
fn saturating_square_properties() {
apply_fn_to_unsigneds!(wrapping_square_properties_helper_unsigned);
apply_fn_to_signeds!(wrapping_square_properties_helper_signed);
}
| {
assert_eq!((-x).wrapping_square(), square);
} | conditional_block |
wrapping_square.rs | use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_wrapping_square() {
fn test<T: PrimitiveInt>(x: T, ou... | assert_eq!(square, x.wrapping_square());
assert_eq!(square, x.wrapping_pow(2));
});
}
fn wrapping_square_properties_helper_signed<T: PrimitiveSigned>() {
signed_gen::<T>().test_properties(|x| {
let mut square = x;
square.wrapping_square_assign();
assert_eq!(square, x.wra... |
fn wrapping_square_properties_helper_unsigned<T: PrimitiveUnsigned>() {
unsigned_gen::<T>().test_properties(|x| {
let mut square = x;
square.wrapping_square_assign(); | random_line_split |
eina_iterator.rs | #![allow(dead_code)]
use eina_ffi::*;
use libc::*;
use std::ptr;
pub struct EinaIterator {
pub ptr: *mut Eina_Iterator,
}
impl EinaIterator {
/// Return the container of an iterator
pub fn get_container(&mut self) -> Option<&mut c_void> {
unsafe {
let container = eina_iterator_contain... |
/// Unlock the container of the iterator
///
/// Warning: None of the existing eina data structures are lockable
pub fn unlock(&mut self) -> bool {
unsafe {
match eina_iterator_unlock(self.ptr) {
EINA_TRUE => true,
_ => false,
}
}
... | {
unsafe {
match eina_iterator_lock(self.ptr) {
EINA_TRUE => true,
_ => false,
}
}
} | identifier_body |
eina_iterator.rs | #![allow(dead_code)]
use eina_ffi::*;
use libc::*;
use std::ptr;
pub struct EinaIterator {
pub ptr: *mut Eina_Iterator,
}
impl EinaIterator {
/// Return the container of an iterator
pub fn get_container(&mut self) -> Option<&mut c_void> {
unsafe {
let container = eina_iterator_contain... | }
} | random_line_split | |
eina_iterator.rs | #![allow(dead_code)]
use eina_ffi::*;
use libc::*;
use std::ptr;
pub struct EinaIterator {
pub ptr: *mut Eina_Iterator,
}
impl EinaIterator {
/// Return the container of an iterator
pub fn get_container(&mut self) -> Option<&mut c_void> {
unsafe {
let container = eina_iterator_contain... | (&mut self) {
unsafe {
eina_iterator_free(self.ptr)
}
}
}
| drop | identifier_name |
htype.rs | use super::{Result, Error};
#[derive(Debug, PartialEq)]
#[allow(non_camel_case_types)]
pub enum | {
Ethernet_10mb = 1,
Experimental_Ethernet_3mb,
Amateur_Radio_AX_25,
Proteon_ProNET_Token_Ring,
Chaos,
IEEE_802_Networks,
Arcnet,
Hyperchannel,
Lanstar,
Autonet_Short_Address,
LocalTalk,
LocalNet,
Ultra_link,
SMDS,
Frame_Relay,
Asynchronous_Transmission_M... | Htype | identifier_name |
htype.rs | use super::{Result, Error};
#[derive(Debug, PartialEq)]
#[allow(non_camel_case_types)]
pub enum Htype {
Ethernet_10mb = 1,
Experimental_Ethernet_3mb,
Amateur_Radio_AX_25,
Proteon_ProNET_Token_Ring,
Chaos,
IEEE_802_Networks,
Arcnet,
Hyperchannel,
Lanstar,
Autonet_Short_Address,
... | 15u8 => Ok(Htype::Frame_Relay),
16u8 => Ok(Htype::Asynchronous_Transmission_Mode),
_ => Err(Error::ParseError(format!("Unknown Htype {:?}", byte)))
}
}
} | random_line_split | |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... |
pub fn split(&self, n_way: usize) -> ThreadInfo<T> {
let subcomm = self.comm.split(self.thread_id, n_way);
let subcomm_id = self.thread_id % (self.comm.n_threads / n_way);
ThreadInfo{ thread_id: subcomm_id, comm: subcomm }
}
}
| { self.thread_id } | identifier_body |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... |
//self.barrier.wait();
}
fn broadcast(&self, info: &ThreadInfo<T>, to_send: *mut T) -> *mut T {
if info.thread_id == 0 {
//Spin while waiting for the thread communicator to be ready to broadcast
while self.slot_reads.load(Ordering::Relaxed)!= self.n_threads {... | {
while self.barrier_sense.load(Ordering::Relaxed) == my_sense { }
} | conditional_block |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... | (&self, info: &ThreadInfo<T>, to_send: *mut T) -> *mut T {
if info.thread_id == 0 {
//Spin while waiting for the thread communicator to be ready to broadcast
while self.slot_reads.load(Ordering::Relaxed)!= self.n_threads {
}
self.slot.store(to_send, Order... | broadcast | identifier_name |
thread_comm.rs | extern crate alloc;
use core::ptr::{self};
use std::sync::{Arc,RwLock};
//use std::sync::{Barrier};
use std::sync::atomic::{AtomicPtr,AtomicUsize,AtomicBool,Ordering};
pub struct ThreadComm<T> {
n_threads: usize,
//Slot has a MatrixBuffer, to be broadcast
slot: AtomicPtr<T>,
//Slot_reads represents t... | //If slot_reads < n_threads, it is ready to be read.
//Each thread is only allowed to read from the slot one time.
//It is incremented every time slot is read,
//And it is an integer modulo n_threads
slot_reads: AtomicUsize,
//barrier: Barrier,
//Stuff for barriers
barrier_sense: Atomi... | //If slot_reads == n_threads, then it is ready to be written to. | random_line_split |
trait-inheritance-subst2.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 (x, y) = (mi(3), mi(5));
let z = f(x, y);
assert_eq!(z.val, 13);
}
| { MyInt { val: v } } | identifier_body |
trait-inheritance-subst2.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 add(&self, other: &MyInt) -> MyInt { self.chomp(other) }
}
impl MyNum for MyInt {}
fn f<T:MyNum>(x: T, y: T) -> T {
return x.add(&y).chomp(&y);
}
fn mi(v: isize) -> MyInt { MyInt { val: v } }
pub fn main() {
let (x, y) = (mi(3), mi(5));
let z = f(x, y);
assert_eq!(z.val, 13);
} | }
impl Add<MyInt, MyInt> for MyInt { | random_line_split |
trait-inheritance-subst2.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 ... | (&self, other: &MyInt) -> MyInt { self.chomp(other) }
}
impl MyNum for MyInt {}
fn f<T:MyNum>(x: T, y: T) -> T {
return x.add(&y).chomp(&y);
}
fn mi(v: isize) -> MyInt { MyInt { val: v } }
pub fn main() {
let (x, y) = (mi(3), mi(5));
let z = f(x, y);
assert_eq!(z.val, 13);
}
| add | identifier_name |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... |
}
});
}
})
})
.collect();
joins.drain(..).map(|join| join.join().unwrap()).count();
})
.join()
.unwrap();
}
| {
let req_len = res.unwrap();
match req.path {
Some(ref _path) => {
let _ = conn.write_all(&RESPONSE.as_bytes())?;
if re... | conditional_block |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... | loop {
let mut headers = [httparse::EMPTY_HEADER; 16];
let len = conn.read(&mut buf[buf_i..])?;
if len == 0 {
return Ok(());
}
... | {
env_logger::init();
let addr = listend_addr();
let listener = TcpListener::bind(&addr).unwrap();
println!("Starting mioco http server on {:?}",
listener.local_addr().unwrap());
mioco::spawn(move || {
let mut joins: Vec<_> = (0..mioco::thread_num())
.map(|_| {
... | identifier_body |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... | () {
env_logger::init();
let addr = listend_addr();
let listener = TcpListener::bind(&addr).unwrap();
println!("Starting mioco http server on {:?}",
listener.local_addr().unwrap());
mioco::spawn(move || {
let mut joins: Vec<_> = (0..mioco::thread_num())
.map(|_| {
... | main | identifier_name |
http-server.rs | extern crate mioco;
extern crate env_logger;
extern crate httparse;
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::{self, Write, Read};
use mioco::net::TcpListener;
const DEFAULT_LISTEN_ADDR: &'static str = "127.0.0.1:5555";
fn listend_addr() -> SocketAddr {
FromStr::from_str(DEFAULT_LISTEN_ADDR).... | }
});
}
})
})
.collect();
joins.drain(..).map(|join| join.join().unwrap()).count();
})
.join()
.unwrap();
} | } | random_line_split |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum Kind {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result... | else {
h.inverse()
} {
Some(ref t) => t.render(r, rc),
None => Ok(()),
}
}
}
fn include_helper(h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
let param = h.param(0)
.ok_or(RenderError::new("Param expected ... | {
h.template()
} | conditional_block |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum Kind {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result... | hb.register_decorator("annotate", Box::new(annotate_decorator));
} | hb.register_helper("if_null", Box::new(IsKind { kind: Kind::Null }));
hb.register_helper("include", Box::new(include_helper)); | random_line_split |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum | {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
let param = h.param(0)
.ok_or(RenderError::new("Param expected... | Kind | identifier_name |
helpers.rs | use handlebars::*;
use serde_json::value::Value;
use serde_json::Map;
#[derive(PartialEq)]
enum Kind {
Object,
Array,
String,
Number,
Boolean,
Null,
}
struct IsKind {
kind: Kind,
}
impl HelperDef for IsKind {
fn call(&self, h: &Helper, r: &Handlebars, rc: &mut RenderContext) -> Result... |
fn annotate_decorator(_: &Decorator,
_: &Handlebars,
rc: &mut RenderContext)
-> Result<(), RenderError> {
fn annotate_map(map: &mut Map<String, Value>) {
for (k, v) in map {
if let Some(ref mut m) = v.as_object_mut().as_mut() {
... | {
let param = h.param(0)
.ok_or(RenderError::new("Param expected for helper"))?;
match param.value().as_str() {
Some(s) => {
match r.get_template(s) {
Some(t) => t.render(r, rc),
None => Err(RenderError::new("Template not found")),
}
... | identifier_body |
gpdma0_ch2.rs | #[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Source Address Register"]
pub sar: crate::Reg<sar::SAR_SPEC>,
_reserved1: [u8; 0x04],
#[doc = "0x08 - Destination Address Register"]
pub dar: crate::Reg<dar::DAR_SPEC>,
_reserved2: [u8; 0x0c],
#[doc = "0x18 - Co... | pub mod dar;
#[doc = "CTLL register accessor: an alias for `Reg<CTLL_SPEC>`"]
pub type CTLL = crate::Reg<ctll::CTLL_SPEC>;
#[doc = "Control Register Low"]
pub mod ctll;
#[doc = "CTLH register accessor: an alias for `Reg<CTLH_SPEC>`"]
pub type CTLH = crate::Reg<ctlh::CTLH_SPEC>;
#[doc = "Control Register High"]
pub mod ... | #[doc = "Destination Address Register"] | random_line_split |
gpdma0_ch2.rs | #[doc = r"Register block"]
#[repr(C)]
pub struct | {
#[doc = "0x00 - Source Address Register"]
pub sar: crate::Reg<sar::SAR_SPEC>,
_reserved1: [u8; 0x04],
#[doc = "0x08 - Destination Address Register"]
pub dar: crate::Reg<dar::DAR_SPEC>,
_reserved2: [u8; 0x0c],
#[doc = "0x18 - Control Register Low"]
pub ctll: crate::Reg<ctll::CTLL_SPEC>... | RegisterBlock | identifier_name |
enums.rs | use parking_lot::RwLock;
use std::collections::hash_map::HashMap;
use std::convert::TryInto;
use std::ops::Index;
use std::sync::Arc;
use dora_parser::ast;
use dora_parser::interner::Name;
use dora_parser::lexer::position::Position;
use crate::language::ty::{SourceType, SourceTypeArray};
use crate::utils::GrowableVe... | };
if let Some(&method_id) = table.get(&name) {
candidates.push(Candidate {
object_type: object_type.clone(),
container_type_params: bindings.clone(),
fct_id: method_id,
});
}
}
}... | &ximpl.static_names
} else {
&ximpl.instance_names | random_line_split |
enums.rs | use parking_lot::RwLock;
use std::collections::hash_map::HashMap;
use std::convert::TryInto;
use std::ops::Index;
use std::sync::Arc;
use dora_parser::ast;
use dora_parser::interner::Name;
use dora_parser::lexer::position::Position;
use crate::language::ty::{SourceType, SourceTypeArray};
use crate::utils::GrowableVe... |
}
}
candidates
}
| {
candidates.push(Candidate {
object_type: object_type.clone(),
container_type_params: bindings.clone(),
fct_id: method_id,
});
} | conditional_block |
enums.rs | use parking_lot::RwLock;
use std::collections::hash_map::HashMap;
use std::convert::TryInto;
use std::ops::Index;
use std::sync::Arc;
use dora_parser::ast;
use dora_parser::interner::Name;
use dora_parser::lexer::position::Position;
use crate::language::ty::{SourceType, SourceTypeArray};
use crate::utils::GrowableVe... | (data: usize) -> EnumInstanceId {
EnumInstanceId(data as u32)
}
}
impl GrowableVec<EnumInstance> {
pub fn idx(&self, index: EnumInstanceId) -> Arc<EnumInstance> {
self.idx_usize(index.0 as usize)
}
}
#[derive(Debug)]
pub struct EnumInstance {
pub id: EnumInstanceId,
pub enum_id: En... | from | identifier_name |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... |
}
games
}
fn calc_data(games: &Vec<Game>) -> HashMap<String, TeamData> {
let mut teams: HashMap<String, TeamData> = HashMap::new();
for game in games {
let ((w1, l1, d1, p1), (w2, l2, d2, p2)) = match game.result {
GameResult::Win => ((1, 0, 0, 3), (0, 1, 0, 0)),
GameRe... | {
games.push(game)
} | conditional_block |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... | (team1: &(&String, &TeamData), team2: &(&String, &TeamData)) -> Ordering {
match team1.1.points.cmp(&team2.1.points) {
Ordering::Equal => {
match team1.1.won.cmp(&team2.1.won) {
Ordering::Equal => team2.0.cmp(&team1.0),
ans @ _ => ans,
}
}
... | custom_sort | identifier_name |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... | {
let games: Vec<Game> = read_input(input);
let results = calc_data(&games);
let content = pretty_print_results(&results);
write_output(&content, output);
Some(games.len())
} | identifier_body | |
lib.rs | use std::fs::File;
use std::path::Path;
use std::str::FromStr;
use std::io::BufReader;
use std::io::prelude::*;
use std::collections::HashMap;
use std::cmp::Ordering;
enum GameResult {
Win,
Loss,
Draw,
}
struct Game {
team1: String,
team2: String,
result: GameResult,
}
struct TeamData {
p... | "win" => GameResult::Win,
"loss" => GameResult::Loss,
"draw" => GameResult::Draw,
_ => return Err("invalid outcame"),
};
Ok(Game {
team1: input[0].into(),
team2: input[1].into(),
result: outcame,
})
}
}
fn r... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.