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 |
|---|---|---|---|---|
c_str.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 ... |
#[test]
fn simple() {
let s = CString::new("1234").unwrap();
assert_eq!(s.as_bytes(), b"1234");
assert_eq!(s.as_bytes_with_nul(), b"1234\0");
}
#[test]
fn build_with_zero1() {
assert!(CString::new(&b"\0"[..]).is_err());
}
#[test]
fn build_with_zero2() {... | {
let data = b"123\0";
let ptr = data.as_ptr() as *const libc::c_char;
unsafe {
assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123");
assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0");
}
} | identifier_body |
ptr.rs | /*!
Typed virtual address.
*/
use std::{cmp, fmt, hash, mem, str};
use std::marker::PhantomData;
use crate::Pod;
use super::image::{Va, SignedVa};
/// Typed virtual address.
#[repr(transparent)]
pub struct Ptr<T:?Sized = ()> {
va: Va,
marker: PhantomData<fn() -> T>
}
impl<T:?Sized> Ptr<T> {
// Work around unsta... | impl<T:?Sized> fmt::Display for Ptr<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let buf = Ptr::fmt(*self);
f.write_str(unsafe { str::from_utf8_unchecked(&buf) })
}
}
#[cfg(feature = "serde")]
impl<T:?Sized> serde::Serialize for Ptr<T> {
fn serialize<S: serde::Serializer>(&self, serializer: S) ->... | random_line_split | |
ptr.rs | /*!
Typed virtual address.
*/
use std::{cmp, fmt, hash, mem, str};
use std::marker::PhantomData;
use crate::Pod;
use super::image::{Va, SignedVa};
/// Typed virtual address.
#[repr(transparent)]
pub struct Ptr<T:?Sized = ()> {
va: Va,
marker: PhantomData<fn() -> T>
}
impl<T:?Sized> Ptr<T> {
// Work around unsta... | (&self, rhs: &Ptr<T>) -> bool {
self.va == rhs.va
}
}
impl<T:?Sized> PartialOrd for Ptr<T> {
fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> {
self.va.partial_cmp(&rhs.va)
}
}
impl<T:?Sized> Ord for Ptr<T> {
fn cmp(&self, rhs: &Ptr<T>) -> cmp::Ordering {
self.va.cmp(&rhs.va)
}
}
impl<T:?Sized> h... | eq | identifier_name |
ptr.rs | /*!
Typed virtual address.
*/
use std::{cmp, fmt, hash, mem, str};
use std::marker::PhantomData;
use crate::Pod;
use super::image::{Va, SignedVa};
/// Typed virtual address.
#[repr(transparent)]
pub struct Ptr<T:?Sized = ()> {
va: Va,
marker: PhantomData<fn() -> T>
}
impl<T:?Sized> Ptr<T> {
// Work around unsta... |
}
impl<T:?Sized> Eq for Ptr<T> {}
impl<T:?Sized> PartialEq for Ptr<T> {
fn eq(&self, rhs: &Ptr<T>) -> bool {
self.va == rhs.va
}
}
impl<T:?Sized> PartialOrd for Ptr<T> {
fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> {
self.va.partial_cmp(&rhs.va)
}
}
impl<T:?Sized> Ord for Ptr<T> {
fn cmp(&self... | {
Ptr::NULL
} | identifier_body |
ptr.rs | /*!
Typed virtual address.
*/
use std::{cmp, fmt, hash, mem, str};
use std::marker::PhantomData;
use crate::Pod;
use super::image::{Va, SignedVa};
/// Typed virtual address.
#[repr(transparent)]
pub struct Ptr<T:?Sized = ()> {
va: Va,
marker: PhantomData<fn() -> T>
}
impl<T:?Sized> Ptr<T> {
// Work around unsta... | else { b'a' + (digit - 10) };
s[i + 2] = chr;
}
return s;
}
}
impl<T> Ptr<[T]> {
/// Decays the pointer from `[T]` to `T`.
pub const fn decay(self) -> Ptr<T> {
Ptr { va: self.va, marker: Ptr::<T>::MARKER }
}
/// Pointer arithmetic, gets the pointer of an element at the specified index.
pub const fn at(s... | { b'0' + digit } | conditional_block |
sniffer_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/. */
| use std::comm::{channel, Receiver, Sender};
use std::task::TaskBuilder;
use resource_task::{TargetedLoadResponse};
pub type SnifferTask = Sender<TargetedLoadResponse>;
pub fn new_sniffer_task() -> SnifferTask {
let(sen, rec) = channel();
let builder = TaskBuilder::new().named("SnifferManager");
builder.sp... | //! A task that sniffs data | random_line_split |
sniffer_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/. */
//! A task that sniffs data
use std::comm::{channel, Receiver, Sender};
use std::task::TaskBuilder;
use resource_t... | (self) {
loop {
match self.data_receiver.recv_opt() {
Ok(snif_data) => {
let _ = snif_data.consumer.send_opt(snif_data.load_response);
}
Err(_) => break,
}
}
}
}
| start | identifier_name |
system.rs | use arguments::Arguments;
use mcpat;
use std::path::Path;
use Result;
use server::Address;
/// A McPAT system.
pub struct System {
backend: mcpat::System,
}
impl System {
/// Open a system.
#[inline]
pub fn | <T: AsRef<Path>>(path: T) -> Result<System> {
let backend = ok!(mcpat::open(path));
{
let system = backend.raw();
if system.number_of_L2s > 0 && system.Private_L2 == 0 {
raise!("shared L2 caches are currently not supported");
}
}
Ok(Sys... | open | identifier_name |
system.rs | use arguments::Arguments;
use mcpat;
use std::path::Path;
use Result;
use server::Address;
/// A McPAT system.
pub struct System {
backend: mcpat::System,
}
impl System {
/// Open a system.
#[inline]
pub fn open<T: AsRef<Path>>(path: T) -> Result<System> {
let backend = ok!(mcpat::open(path))... | Ok(ok!(self.backend.compute()))
}
/// Return the number of cores.
pub fn cores(&self) -> usize {
let system = self.backend.raw();
if system.homogeneous_cores!= 0 { 1 } else {
system.number_of_cores as usize
}
}
/// Return the number of L3 caches.
pub... | pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> { | random_line_split |
system.rs | use arguments::Arguments;
use mcpat;
use std::path::Path;
use Result;
use server::Address;
/// A McPAT system.
pub struct System {
backend: mcpat::System,
}
impl System {
/// Open a system.
#[inline]
pub fn open<T: AsRef<Path>>(path: T) -> Result<System> {
let backend = ok!(mcpat::open(path))... |
/// Perform the computation of area and power.
#[inline]
pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> {
Ok(ok!(self.backend.compute()))
}
/// Return the number of cores.
pub fn cores(&self) -> usize {
let system = self.backend.raw();
if system.homogeneo... | {
mcpat::optimize_for_clock_rate(true);
if arguments.get::<bool>("caching").unwrap_or(false) {
let Address(host, port) = arguments.get::<String>("server")
.and_then(|s| Address::parse(&s))
.unwrap_o... | identifier_body |
system.rs | use arguments::Arguments;
use mcpat;
use std::path::Path;
use Result;
use server::Address;
/// A McPAT system.
pub struct System {
backend: mcpat::System,
}
impl System {
/// Open a system.
#[inline]
pub fn open<T: AsRef<Path>>(path: T) -> Result<System> {
let backend = ok!(mcpat::open(path))... |
}
}
| {
system.number_of_L3s as usize
} | conditional_block |
lib.rs | // Copyright 2015 Corey Farwell
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wr... | ) {
let rss_str = "\
<rss>\
<channel>\
</channel>\
</rss>";
assert!(Rss::from_str(rss_str).is_err());
}
#[test]
fn test_read_one_channel() {
let rss_str = "\
<rss>\
<channel>\
<ti... | est_read_one_channel_no_properties( | identifier_name |
lib.rs | // Copyright 2015 Corey Farwell
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wr... | assert_eq!(rss.to_string(), "<?xml version=\'1.0\' encoding=\'UTF-8\'?><rss version=\'2.0\'><channel><title>My Blog</title><link>http://myblog.com</link><description>Where I write stuff</description><item><title>My first post!</title><link>http://myblog.com/post1</link><description>This is my first post</descri... | let rss = Rss(channel); | random_line_split |
job.rs | use std::io::{self, BufRead, Read};
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr;
use crate::{raw, Error};
pub struct JobDriver<R> {
input: R,
job: Job,
input_ended: bool,
}
pub struct Job(pub *mut raw::rs_job_t);
// Wrapper around rs_buffers_t.
struct Buffers<'a> {
inner: raw::rs... | next_out: out_buf.as_mut_ptr() as *mut i8,
avail_out: out_buf.len(),
},
_phantom: PhantomData,
}
}
pub fn with_no_out(in_buf: &'a [u8], eof_in: bool) -> Self {
Buffers {
inner: raw::rs_buffers_t {
next_in: in_bu... | eof_in: if eof_in { 1 } else { 0 }, | random_line_split |
job.rs | use std::io::{self, BufRead, Read};
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr;
use crate::{raw, Error};
pub struct JobDriver<R> {
input: R,
job: Job,
input_ended: bool,
}
pub struct Job(pub *mut raw::rs_job_t);
// Wrapper around rs_buffers_t.
struct Buffers<'a> {
inner: raw::rs... |
pub fn into_inner(self) -> R {
self.input
}
/// Complete the job by working without an output buffer.
///
/// If the job needs to write some data, an `ErrorKind::WouldBlock` error is returned.
pub fn consume_input(&mut self) -> io::Result<()> {
loop {
let (res, rea... | {
JobDriver {
input,
job,
input_ended: false,
}
} | identifier_body |
job.rs | use std::io::{self, BufRead, Read};
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr;
use crate::{raw, Error};
pub struct JobDriver<R> {
input: R,
job: Job,
input_ended: bool,
}
pub struct Job(pub *mut raw::rs_job_t);
// Wrapper around rs_buffers_t.
struct Buffers<'a> {
inner: raw::rs... | (&self) -> usize {
self.inner.avail_out
}
}
| available_output | identifier_name |
main.rs | /*
--- Day 2: Bathroom Security ---
You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code.
"In order to improve ... | (c : char) -> Direction {
match c {
'U' => Direction::Up,
'D' => Direction::Down,
'L' => Direction::Left,
'R' => Direction::Right,
_ => Direction::Up,
}
}
fn move_cursor(numpad : &Numpad, cursor: &Cursor, dir : &Direction) -> Cursor {
// calculate new position of t... | char_to_direction | identifier_name |
main.rs | /*
--- Day 2: Bathroom Security ---
You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code.
"In order to improve ... | None, Some('A'), Some('B'), Some('C'), None,
None, None, Some('D'), None, None
];
// and lets create our cursor, starting at the Five key
let mut cursor : Cursor = 10;
// convert characters to directions
for line in lines {
let sequence : Vec... | {
// read input from the file
let mut f = File::open("input.txt").unwrap();
let mut input = String::new();
f.read_to_string(&mut input).ok();
// split into lines
let lines : Vec<&str> = input.split('\n').collect();
let mut digits : Vec<char> = Vec::new();
// recreate the keypad with t... | identifier_body |
main.rs | /*
--- Day 2: Bathroom Security ---
You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code.
"In order to improve ... | else {
*cursor
}
},
}
}
fn is_valid(numpad: &Numpad, cursor : &Cursor) -> bool {
numpad.get(*cursor).unwrap().is_some()
}
fn digit_for_cursor(numpad : &Numpad, cursor : &Cursor) -> char {
numpad.get(*cursor).unwrap().unwrap().to_owned()
} | {
cursor + row_length
} | conditional_block |
main.rs | /*
--- Day 2: Bathroom Security ---
You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code.
"In order to improve ... | You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different:
You start at "5" and don't move at all (up and left are both edges), ending at 5.
Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at ... | D | random_line_split |
mod.rs | use collections::{Set, set};
use lr1::core::*;
use lr1::first::FirstSets;
use lr1::state_graph::StateGraph;
use grammar::repr::*;
mod reduce;
mod shift;
mod trace_graph;
pub struct | <'trace, 'grammar: 'trace> {
states: &'trace [LR1State<'grammar>],
first_sets: &'trace FirstSets,
state_graph: StateGraph,
trace_graph: TraceGraph<'grammar>,
visited_set: Set<(StateIndex, NonterminalString)>,
}
impl<'trace, 'grammar> Tracer<'trace, 'grammar> {
pub fn new(first_sets: &'trace Fir... | Tracer | identifier_name |
mod.rs | use collections::{Set, set};
use lr1::core::*;
use lr1::first::FirstSets;
use lr1::state_graph::StateGraph;
use grammar::repr::*;
mod reduce;
mod shift;
mod trace_graph;
pub struct Tracer<'trace, 'grammar: 'trace> {
states: &'trace [LR1State<'grammar>],
first_sets: &'trace FirstSets,
state_graph: StateGra... |
}
pub use self::trace_graph::TraceGraph;
| {
Tracer {
states: states,
first_sets: first_sets,
state_graph: StateGraph::new(states),
trace_graph: TraceGraph::new(),
visited_set: set(),
}
} | identifier_body |
mod.rs | use collections::{Set, set};
use lr1::core::*;
use lr1::first::FirstSets;
use lr1::state_graph::StateGraph; | use grammar::repr::*;
mod reduce;
mod shift;
mod trace_graph;
pub struct Tracer<'trace, 'grammar: 'trace> {
states: &'trace [LR1State<'grammar>],
first_sets: &'trace FirstSets,
state_graph: StateGraph,
trace_graph: TraceGraph<'grammar>,
visited_set: Set<(StateIndex, NonterminalString)>,
}
impl<'t... | random_line_split | |
dom.rs |
}
/// An iterator over the DOM children of a node.
pub struct DomChildren<N>(Option<N>);
impl<N> Iterator for DomChildren<N>
where
N: TNode,
{
type Item = N;
fn next(&mut self) -> Option<N> {
let n = self.0.take()?;
self.0 = n.next_sibling();
Some(n)
}
}
/// An iterator over ... | {
loop {
let n = self.0.next()?;
// Filter out nodes that layout should ignore.
if n.is_text_node() || n.is_element() {
return Some(n);
}
}
} | identifier_body | |
dom.rs | #[cfg_attr(feature = "servo", derive(MallocSizeOf, Deserialize, Serialize))]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
self.0
}
}
/// Simple trait to provide basic information about th... | /// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] | random_line_split | |
dom.rs | Option<N>);
impl<N> Iterator for DomChildren<N>
where
N: TNode,
{
type Item = N;
fn next(&mut self) -> Option<N> {
let n = self.0.take()?;
self.0 = n.next_sibling();
Some(n)
}
}
/// An iterator over the DOM descendants of a node in pre-order.
pub struct DomDescendants<N> {
... | (&self) -> DomChildren<Self> {
DomChildren(self.first_child())
}
/// Returns whether the node is attached to a document.
fn is_in_document(&self) -> bool;
/// Iterate over the DOM children of a node, in preorder.
fn dom_descendants(&self) -> DomDescendants<Self> {
DomDescendants {
... | dom_children | identifier_name |
main.rs | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright (C) 2015-2022 Christian Krause *
* *
* ... | () -> Result<()> {
let args = cli::build().get_matches();
let config = Config::try_from(&args)?;
let input = args.value_of("input").unwrap();
analysis::run(input, config)
}
| main | identifier_name |
main.rs | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright (C) 2015-2022 Christian Krause *
* *
* ... | #![warn(clippy::pedantic, clippy::nursery, clippy::cargo)]
mod analysis;
mod cli;
mod config;
mod log;
mod output;
mod summary;
use anyhow::Result;
use crate::config::Config;
fn main() -> Result<()> {
let args = cli::build().get_matches();
let config = Config::try_from(&args)?;
let input = args.value_o... | #![deny(clippy::all)] | random_line_split |
main.rs | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright (C) 2015-2022 Christian Krause *
* *
* ... | {
let args = cli::build().get_matches();
let config = Config::try_from(&args)?;
let input = args.value_of("input").unwrap();
analysis::run(input, config)
} | identifier_body | |
meth.rs | method: &ast::method,
param_substs: Option<@param_substs>,
llfn: ValueRef) {
// figure out how self is being passed
let self_arg = match method.explicit_self.node {
ast::sty_static => {
no_self
}
_ => {
// determine the (mo... | (bcx: @mut Block,
mth_did: ast::DefId,
callee_id: ast::NodeId,
rcvr_substs: &[ty::t],
rcvr_origins: typeck::vtable_res)
-> (~[ty::t], typeck... | combine_impl_and_methods_tps | identifier_name |
meth.rs | use lib;
use metadata::csearch;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee::*;
use middle::trans::callee;
use middle::trans::common::*;
use middle::trans::datum::*;
use middle::trans::expr::{SaveIn, Ignore};
use middle::trans::expr;
use middle::trans::glue;
use middle::trans::mon... | use back::abi;
use lib::llvm::llvm;
use lib::llvm::ValueRef; | random_line_split | |
meth.rs | method: &ast::method,
param_substs: Option<@param_substs>,
llfn: ValueRef) {
// figure out how self is being passed
let self_arg = match method.explicit_self.node {
ast::sty_static => {
no_self
}
_ => {
// determine the (mo... | //
// fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...}
//
// So when we see a call to this function foo, we have to figure
// out which impl the `Trait<T1...Tn>` bound on the type `self` was
// bound to.
let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id).
generics.t... | {
let _icx = push_ctxt("impl::trans_static_method_callee");
let ccx = bcx.ccx();
debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \
callee_id={:?})",
method_id,
ty::item_path_str(bcx.tcx(), trait_id),
callee_id);
let _indenter = indenter();
... | identifier_body |
rotate_turn.rs | use rune_vm::Rune;
use game_state::GameState;
use minion_card::UID;
use ::tags_list::*;
use runes::remove_tag::RemoveTag;
use runes::set_base_mana::SetBaseMana;
use runes::set_mana::SetMana;
use runes::deal_card::DealCard;
use controller::EControllerState;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub... |
game_state.set_on_turn_player(turn_index);
let new_mana =
game_state.get_controller_by_index(turn_index as usize).get_base_mana().clone() + 1;
let sbm = SetBaseMana::new(game_state.get_controller_by_index(turn_index as usize)
.get_uid()
... | {
turn_index = 0;
} | conditional_block |
rotate_turn.rs | use rune_vm::Rune;
use game_state::GameState;
use minion_card::UID;
use ::tags_list::*;
use runes::remove_tag::RemoveTag;
use runes::set_base_mana::SetBaseMana;
use runes::set_mana::SetMana;
use runes::deal_card::DealCard;
use controller::EControllerState;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub... | }
}
implement_for_lua!(RotateTurn, |mut _metatable| {});
impl Rune for RotateTurn {
fn execute_rune(&self, mut game_state: &mut GameState) {
let mut turn_index = game_state.get_on_turn_player().clone();
let in_play = game_state.get_controller_by_index(turn_index as usize).get_copy_of_in_play(... | impl RotateTurn {
pub fn new() -> RotateTurn {
RotateTurn {} | random_line_split |
rotate_turn.rs | use rune_vm::Rune;
use game_state::GameState;
use minion_card::UID;
use ::tags_list::*;
use runes::remove_tag::RemoveTag;
use runes::set_base_mana::SetBaseMana;
use runes::set_mana::SetMana;
use runes::deal_card::DealCard;
use controller::EControllerState;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub... | (&self, _controller: UID, _game_state: &GameState) -> bool {
return true;
}
fn to_json(&self) -> String {
"{\"runeType\":\"RotateTurn\"}".to_string()
}
fn into_box(&self) -> Box<Rune> {
Box::new(self.clone())
}
}
| can_see | identifier_name |
main.rs | extern crate log;
extern crate env_logger;
extern crate clap;
extern crate ctrlc;
extern crate gauc;
extern crate iron;
extern crate urlencoded;
use clap::{App, Arg};
use gauc::cli;
use gauc::web;
use gauc::client::Client;
use std::env;
use std::process::exit;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{At... | }
} | if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) {
web::start_web(&Arc::new(Mutex::new(client)), port);
} | random_line_split |
main.rs | extern crate log;
extern crate env_logger;
extern crate clap;
extern crate ctrlc;
extern crate gauc;
extern crate iron;
extern crate urlencoded;
use clap::{App, Arg};
use gauc::cli;
use gauc::web;
use gauc::client::Client;
use std::env;
use std::process::exit;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{At... |
/// Web Server Entrypoint
fn main() {
install_ctrl_c_handler();
let couchbase_uri = match env::var("COUCHBASE_URI") {
Ok(uri) => uri,
Err(_) => DEFAULT_URI.to_string()
};
// Specify program options
let matches = App::new(DESCRIPTION)
.version(VERSION)
.author("Toma... | {
let running = Arc::new(AtomicBool::new(true));
let r = Arc::clone(&running);
let _ = ctrlc::set_handler(move || {
println!("");
println!("");
println!("Received ctrl+c, exiting ...");
r.store(false, Ordering::SeqCst);
exit(0);
});
} | identifier_body |
main.rs | extern crate log;
extern crate env_logger;
extern crate clap;
extern crate ctrlc;
extern crate gauc;
extern crate iron;
extern crate urlencoded;
use clap::{App, Arg};
use gauc::cli;
use gauc::web;
use gauc::client::Client;
use std::env;
use std::process::exit;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{At... |
let port: u16 = matches.value_of("rest-port").unwrap().to_string().parse::<u16>().unwrap();
if matches.is_present("rest") {
if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) {
web::start_web(&Arc::new(Mutex::new(client)), port);
}
}
}
| {
if let Ok(mut client) = Client::connect(matches.value_of("url").unwrap()) {
cli::main(&matches, &mut client);
}
} | conditional_block |
main.rs | extern crate log;
extern crate env_logger;
extern crate clap;
extern crate ctrlc;
extern crate gauc;
extern crate iron;
extern crate urlencoded;
use clap::{App, Arg};
use gauc::cli;
use gauc::web;
use gauc::client::Client;
use std::env;
use std::process::exit;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{At... | () {
install_ctrl_c_handler();
let couchbase_uri = match env::var("COUCHBASE_URI") {
Ok(uri) => uri,
Err(_) => DEFAULT_URI.to_string()
};
// Specify program options
let matches = App::new(DESCRIPTION)
.version(VERSION)
.author("Tomas Korcak <korczis@gmail.com>")
... | main | identifier_name |
task.rs | use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::str::FromStr;
use chrono::NaiveDate;
use todo_txt::Task as RawTask;
/// A Task with its metadata
#[derive(Clone, Debug, PartialEq)]
pub struct Task {
pub subject: String,
pub priority: u8,
pub creation_date: Option<NaiveDate>,
pub statu... | ;
Task {
subject: t.subject,
priority: t.priority,
creation_date: t.create_date,
status,
threshold_date: t.threshold_date,
due_date: t.due_date,
contexts: t.contexts,
projects: t.projects,
hashtags: t.ha... | {
Status::Started
} | conditional_block |
task.rs | use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::str::FromStr;
use chrono::NaiveDate;
use todo_txt::Task as RawTask;
/// A Task with its metadata
#[derive(Clone, Debug, PartialEq)]
pub struct Task {
pub subject: String,
pub priority: u8,
pub creation_date: Option<NaiveDate>,
pub statu... | due_date: self.due_date,
contexts: self.contexts,
projects: self.projects,
hashtags: self.hashtags,
tags: self.tags,
}
}
} | create_date: self.creation_date,
finished,
finish_date,
threshold_date: self.threshold_date, | random_line_split |
task.rs | use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::str::FromStr;
use chrono::NaiveDate;
use todo_txt::Task as RawTask;
/// A Task with its metadata
#[derive(Clone, Debug, PartialEq)]
pub struct Task {
pub subject: String,
pub priority: u8,
pub creation_date: Option<NaiveDate>,
pub statu... | (txt: impl Borrow<str>) -> Task {
// For this unwrap, see https://github.com/sanpii/todo-txt/issues/10
RawTask::from_str(txt.borrow()).unwrap().into()
}
/// Check if the task is done
pub fn is_done(&self) -> bool {
if let Status::Finished(_) = self.status {
true
... | parse | identifier_name |
task.rs | use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::str::FromStr;
use chrono::NaiveDate;
use todo_txt::Task as RawTask;
/// A Task with its metadata
#[derive(Clone, Debug, PartialEq)]
pub struct Task {
pub subject: String,
pub priority: u8,
pub creation_date: Option<NaiveDate>,
pub statu... | }
}
impl ::std::convert::Into<RawTask> for Task {
fn into(self) -> RawTask {
let (finished, finish_date) = match self.status {
Status::Started => (false, None),
Status::Finished(date) => (true, date),
};
RawTask {
subject: self.subject,
p... | {
// compute status
let status = if t.finished {
Status::Finished(t.finish_date)
} else {
Status::Started
};
Task {
subject: t.subject,
priority: t.priority,
creation_date: t.create_date,
status,
... | identifier_body |
timeout.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
use std::time::{Duration, Instant};
// The whole point of this test is to take an excessively long execution
// and make sure it terminates about on time if a limiter is provided
#[test]
pub fn infinity() | }
| {
single(&|holmes: &mut Engine, core: &mut Core| {
// Amount of time holmes gets
let limit = Duration::new(2, 0);
// Wiggle room to shut things down
let wiggle = Duration::new(1, 0);
holmes.limit_time(limit.clone());
let start = Instant::now();
try!(holmes_exe... | identifier_body |
timeout.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
use std::time::{Duration, Instant};
// The whole point of this test is to take an excessively long execution
// and make sure it terminates about on time if a limiter is provided
#[test]
pub fn infinity() {
single(&|holmes: &mut Engine, core: &mut Core| {
... | holmes.limit_time(limit.clone());
let start = Instant::now();
try!(holmes_exec!(holmes, {
predicate!(count(uint64));
fact!(count(0));
func!(let inc: uint64 -> uint64 = |i: &u64| *i + 1);
rule!(inc: count(n_plus_one) <= count(n), {
let n_plus_one = {inc([n])}
... | random_line_split | |
timeout.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
use std::time::{Duration, Instant};
// The whole point of this test is to take an excessively long execution
// and make sure it terminates about on time if a limiter is provided
#[test]
pub fn | () {
single(&|holmes: &mut Engine, core: &mut Core| {
// Amount of time holmes gets
let limit = Duration::new(2, 0);
// Wiggle room to shut things down
let wiggle = Duration::new(1, 0);
holmes.limit_time(limit.clone());
let start = Instant::now();
try!(holmes_... | infinity | identifier_name |
cell_renderer_toggle.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Renders a toggle button in a cell
use ffi;
use glib::{to_bool, to_gboolean};
struct... | }
}
impl_drop!(CellRendererToggle);
impl_TraitWidget!(CellRendererToggle);
impl ::CellRendererTrait for CellRendererToggle {} | unsafe {
ffi::gtk_cell_renderer_toggle_set_active(
self.pointer as *mut ffi::C_GtkCellRendererToggle, to_gboolean(active));
} | random_line_split |
cell_renderer_toggle.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Renders a toggle button in a cell
use ffi;
use glib::{to_bool, to_gboolean};
struct... |
pub fn get_radio(&self) -> bool {
unsafe {
to_bool(ffi::gtk_cell_renderer_toggle_get_radio(
self.pointer as *mut ffi::C_GtkCellRendererToggle))
}
}
pub fn set_radio(&self, radio: bool) -> () {
unsafe {
ffi::gtk_cell_renderer_toggle_set_r... | {
let tmp_pointer = unsafe { ffi::gtk_cell_renderer_toggle_new() as *mut ffi::C_GtkWidget };
check_pointer!(tmp_pointer, CellRendererToggle)
} | identifier_body |
cell_renderer_toggle.rs | // Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Renders a toggle button in a cell
use ffi;
use glib::{to_bool, to_gboolean};
struct... | () -> Option<CellRendererToggle> {
let tmp_pointer = unsafe { ffi::gtk_cell_renderer_toggle_new() as *mut ffi::C_GtkWidget };
check_pointer!(tmp_pointer, CellRendererToggle)
}
pub fn get_radio(&self) -> bool {
unsafe {
to_bool(ffi::gtk_cell_renderer_toggle_get_radio(
... | new | identifier_name |
sendfn-generic-fn.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 spawn<A:Copy,B:Copy>(f: extern fn(&~fn(A,B)->Pair<A,B>)) {
let arg: ~fn(A, B) -> Pair<A,B> = |a, b| make_generic_record(a, b);
task::spawn(|| f(&arg));
}
fn test05() {
spawn::<float,~str>(test05_start);
} | random_line_split | |
sendfn-generic-fn.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 ... | (f: &~fn(v: float, v: ~str) -> Pair<float, ~str>) {
let p = (*f)(22.22f, ~"Hi");
info!(copy p);
assert!(p.a == 22.22f);
assert!(p.b == ~"Hi");
let q = (*f)(44.44f, ~"Ho");
info!(copy q);
assert!(q.a == 44.44f);
assert!(q.b == ~"Ho");
}
fn spawn<A:Copy,B:Copy>(f: extern fn(&~fn(A,B)->Pa... | test05_start | identifier_name |
sendfn-generic-fn.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 ... |
struct Pair<A,B> { a: A, b: B }
fn make_generic_record<A:Copy,B:Copy>(a: A, b: B) -> Pair<A,B> {
return Pair {a: a, b: b};
}
fn test05_start(f: &~fn(v: float, v: ~str) -> Pair<float, ~str>) {
let p = (*f)(22.22f, ~"Hi");
info!(copy p);
assert!(p.a == 22.22f);
assert!(p.b == ~"Hi");
let q = ... | { test05(); } | identifier_body |
dragon.rs | // Copyright 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-MIT or ... | else {
mant.mul_pow2(d.exp as usize);
minus.mul_pow2(d.exp as usize);
plus.mul_pow2(d.exp as usize);
}
// divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as us... | {
scale.mul_pow2(-d.exp as usize);
} | conditional_block |
dragon.rs | // Copyright 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-MIT or ... | <'a>(x: &'a mut Big, scale: &Big,
scale2: &Big, scale4: &Big, scale8: &Big) -> (u8, &'a mut Big) {
let mut d = 0;
if *x >= *scale8 { x.sub(scale8); d += 8; }
if *x >= *scale4 { x.sub(scale4); d += 4; }
if *x >= *scale2 { x.sub(scale2); d += 2; }
if *x >= *scale { x.sub(scale)... | div_rem_upto_16 | identifier_name |
dragon.rs | // Copyright 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-MIT or ... | } else {
mul_pow10(&mut mant, -k as usize);
mul_pow10(&mut minus, -k as usize);
mul_pow10(&mut plus, -k as usize);
}
// fixup when `mant + plus > scale` (or `>=`).
// we are not actually modifying `scale`, since we can skip the initial multiplication instead.
// now `scale <... | }
// divide `mant` by `10^k`. now `scale / 10 < mant + plus <= scale * 10`.
if k >= 0 {
mul_pow10(&mut scale, k as usize); | random_line_split |
dragon.rs | // Copyright 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-MIT or ... | if k >= 0 {
mul_pow10(&mut scale, k as usize);
} else {
mul_pow10(&mut mant, -k as usize);
}
// fixup when `mant + plus >= scale`, where `plus / scale = 10^-buf.len() / 2`.
// in order to keep the fixed-size bignum, we actually use `mant + floor(plus) >= scale`.
// we are not ac... | {
assert!(d.mant > 0);
assert!(d.minus > 0);
assert!(d.plus > 0);
assert!(d.mant.checked_add(d.plus).is_some());
assert!(d.mant.checked_sub(d.minus).is_some());
// estimate `k_0` from original inputs satisfying `10^(k_0-1) < v <= 10^(k_0+1)`.
let mut k = estimate_scaling_factor(d.mant, d.ex... | identifier_body |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... | records::generate(env, root_path, &mut mod_rs);
enums::generate(env, root_path, &mut mod_rs);
flags::generate(env, root_path, &mut mod_rs);
alias::generate(env, root_path, &mut mod_rs);
functions::generate(env, root_path, &mut mod_rs);
constants::generate(env, root_path, &mut mod_rs);
gener... | generate_single_version_file(env);
objects::generate(env, root_path, &mut mod_rs, &mut traits); | random_line_split |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... | (env: &Env) {
if let Some(ref path) = env.config.single_version_file {
save_to_file(path, env.config.make_backup, |w| {
general::single_version_file(w, &env.config)
});
}
}
| generate_single_version_file | identifier_name |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... |
pub fn generate_mod_rs(env: &Env, root_path: &Path, mod_rs: &[String], traits: &[String]) {
let path = root_path.join("mod.rs");
save_to_file(path, env.config.make_backup, |w| {
general::start_comments(w, &env.config)?;
general::write_vec(w, mod_rs)?;
writeln!(w)?;
writeln!(w, ... | {
let mut mod_rs: Vec<String> = Vec::new();
let mut traits: Vec<String> = Vec::new();
let root_path = env.config.auto_path.as_path();
generate_single_version_file(env);
objects::generate(env, root_path, &mut mod_rs, &mut traits);
records::generate(env, root_path, &mut mod_rs);
enums::genera... | identifier_body |
mod.rs | use crate::{config::WorkMode, env::Env, file_saver::*};
use std::path::Path;
mod alias;
mod child_properties;
mod constants;
mod doc;
mod enums;
mod flags;
pub mod function;
mod function_body_chunk;
mod functions;
mod general;
mod object;
mod objects;
mod parameter;
mod properties;
mod property_body;
mod record;
mod r... |
}
| {
save_to_file(path, env.config.make_backup, |w| {
general::single_version_file(w, &env.config)
});
} | conditional_block |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct Portal {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self |
}
pub struct PortalSystem;
impl specs::System<app::UpdateContext> for PortalSystem {
fn run(&mut self, arg: specs::RunArg, context: app::UpdateContext) {
let (grid_squares, players, states, portals, entities) = arg.fetch(|world| {
(
world.read::<GridSquare>(),
w... | {
Portal {
destination: destination,
}
} | identifier_body |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct Portal {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self {
Portal {
des... |
}
}
}
}
| {
context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap();
} | conditional_block |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct Portal {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self {
Portal {
des... | if (player_pos[0] - pos[0]).powi(2) + (player_pos[1] - pos[1]).powi(2) < 0.01 {
context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap();
}
}
}
}
} | for (portal,entity) in (&portals, &entities).iter() {
let pos = grid_squares.get(entity).expect("portal expect grid square component").position; | random_line_split |
portal.rs | use app;
use components::*;
use specs::Join;
use specs;
use levels;
#[derive(Clone)]
pub struct | {
destination: levels::Level,
}
impl specs::Component for Portal {
type Storage = specs::VecStorage<Self>;
}
impl Portal {
pub fn new(destination: levels::Level) -> Self {
Portal {
destination: destination,
}
}
}
pub struct PortalSystem;
impl specs::System<app::UpdateContex... | Portal | identifier_name |
base64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | * # Example
*
* This converts a string literal to base64 and back.
*
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, FromBase64, STANDARD};
*
* fn main () {
* let hello_str = bytes!("Hello, World").to_base64(STANDARD);
* println!("ba... | * | random_line_split |
base64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
#[test]
fn test_to_base64_url_safe() {
assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_strbuf());
assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_strbuf());
}
#[test]
fn test_from_base64_basic() {
assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes());
... | {
assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zg".to_strbuf());
assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), "Zm8".to_strbuf());
} | identifier_body |
base64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InvalidBase64Character(ch, idx) =>
write!(f, "Invalid character '{}' at position {}", ch, idx),
InvalidBase64Length => write!(f, "Invalid length"),
}
}
}
impl<'a> FromBase64 for &'a str {
/**
... | fmt | identifier_name |
lib.rs | const u8 {
self.data.borrow().as_ptr()
}
}
/// A slower reflection-based arena that can allocate objects of any type.
///
/// This arena uses `Vec<u8>` as a backing store to allocate objects from. For
/// each allocated object, the arena stores a pointer to the type descriptor
/// followed by the object (p... | {
let arena = TypedArena::new();
b.iter(|| {
arena.alloc(Noncopy {
string: "hello world".to_string(),
array: vec!( 1, 2, 3, 4, 5 ),
})
})
} | identifier_body | |
lib.rs | = "27812")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
#![feature(alloc)]
#![feat... |
let ptr: &mut T = unsafe {
let ptr: &mut T = &mut *(self.ptr.get() as *mut T);
ptr::write(ptr, object);
self.ptr.set(self.ptr.get().offset(1));
ptr
};
ptr
}
/// Grows the arena.
#[inline(never)]
fn grow(&self) {
unsafe {... | {
self.grow()
} | conditional_block |
lib.rs | = "27812")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
#![feature(alloc)]
#![feat... | <T> {
/// A pointer to the next object to be allocated.
ptr: Cell<*const T>,
/// A pointer to the end of the allocated area. When this pointer is
/// reached, a new chunk is allocated.
end: Cell<*const T>,
/// A pointer to the first arena segment.
first: RefCell<*mut TypedArenaChunk<T>>,
... | TypedArena | identifier_name |
lib.rs | Rc;
use std::rt::heap::{allocate, deallocate};
// The way arena uses arrays is really deeply awful. The arrays are
// allocated, and have capacities reserved, but the fill for the array
// will always stay at 0.
#[derive(Clone, PartialEq)]
struct Chunk {
data: Rc<RefCell<Vec<u8>>>,
fill: Cell<usize>,
is_co... | array: vec!( 1, 2, 3, 4, 5 ),
});
}
}
| random_line_split | |
rom_nist256_32.rs | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this f... | pub const AESKEY: usize = 16; | pub const SIGN_OF_X: SignOfX = SignOfX::NOT;
pub const HASH_TYPE: usize = 32; | random_line_split |
shootout-nbody.rs | use std::f64;
use std::from_str::FromStr;
use std::os;
use std::uint::range;
use std::vec;
static PI: f64 = 3.141592653589793;
static SOLAR_MASS: f64 = 4.0 * PI * PI;
static YEAR: f64 = 365.24;
static N_BODIES: uint = 5;
static BODIES: [Planet,..N_BODIES] = [
// Sun
Planet {
x: [ 0.0, 0.0, 0.0 ],
... | d[2] = bodies[i].x[2] - bodies[j].x[2];
let d2 = d[0]*d[0] + d[1]*d[1] + d[2]*d[2];
let mag = dt / (d2 * f64::sqrt(d2));
let a_mass = bodies[i].mass;
let b_mass = bodies[j].mass;
bodies[i].v[0] -= d[0] * b_mass * mag;
... | for range(0, N_BODIES) |i| {
for range(i + 1, N_BODIES) |j| {
d[0] = bodies[i].x[0] - bodies[j].x[0];
d[1] = bodies[i].x[1] - bodies[j].x[1]; | random_line_split |
shootout-nbody.rs | use std::f64;
use std::from_str::FromStr;
use std::os;
use std::uint::range;
use std::vec;
static PI: f64 = 3.141592653589793;
static SOLAR_MASS: f64 = 4.0 * PI * PI;
static YEAR: f64 = 365.24;
static N_BODIES: uint = 5;
static BODIES: [Planet,..N_BODIES] = [
// Sun
Planet {
x: [ 0.0, 0.0, 0.0 ],
... | bodies[j].v[2] += d[2] * a_mass * mag;
}
}
for bodies.mut_iter().advance |a| {
a.x[0] += dt * a.v[0];
a.x[1] += dt * a.v[1];
a.x[2] += dt * a.v[2];
}
}
}
fn energy(bodies: &[Planet,..N_BODIES]) -> f64 {
let mut e = 0.0;
... | {
let mut d = [ 0.0, ..3 ];
for (steps as uint).times {
for range(0, N_BODIES) |i| {
for range(i + 1, N_BODIES) |j| {
d[0] = bodies[i].x[0] - bodies[j].x[0];
d[1] = bodies[i].x[1] - bodies[j].x[1];
d[2] = bodies[i].x[2] - bodies[j].x[2];
... | identifier_body |
shootout-nbody.rs | use std::f64;
use std::from_str::FromStr;
use std::os;
use std::uint::range;
use std::vec;
static PI: f64 = 3.141592653589793;
static SOLAR_MASS: f64 = 4.0 * PI * PI;
static YEAR: f64 = 365.24;
static N_BODIES: uint = 5;
static BODIES: [Planet,..N_BODIES] = [
// Sun
Planet {
x: [ 0.0, 0.0, 0.0 ],
... | () {
let n: i32 = FromStr::from_str(os::args()[1]).get();
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println(fmt!("%.9f", energy(&bodies) as float));
advance(&mut bodies, 0.01, n);
println(fmt!("%.9f", energy(&bodies) as float));
}
| main | identifier_name |
sdl.rs | #![allow(non_camel_case_types)]
#![allow(dead_code)]
use std::os::raw::{c_int, c_uint, c_char, c_void};
pub type Uint8 = u8;
pub type Uint32 = u32;
pub type Sint32 = i32;
pub type Uint16 = i16;
pub type SDL_Keycode = Sint32;
#[repr(u32)]
#[derive(Copy,Clone)]
pub enum SDL_BlendMode{
NONE = 0x00000000,
BLEND ... | COMMA = 54,
PERIOD = 55,
SLASH = 56,
CAPSLOCK = 57,
F1 = 58,
F2 = 59,
F3 = 60,
F4 = 61,
F5 = 62,
F6 = 63,
F7 = 64,
F8 = 65,
F9 = 66,
F10 = 67,
F11 = 68,
F12 = 69,
PRINTSCREEN = 70,
SCROLLLOCK = 71,
PAUSE = 72,
INSERT = 73,
HOME = 74,
... | BACKSLASH = 49,
NONUSHASH = 50,
SEMICOLON = 51,
APOSTROPHE = 52,
GRAVE = 53, | random_line_split |
sdl.rs |
#![allow(non_camel_case_types)]
#![allow(dead_code)]
use std::os::raw::{c_int, c_uint, c_char, c_void};
pub type Uint8 = u8;
pub type Uint32 = u32;
pub type Sint32 = i32;
pub type Uint16 = i16;
pub type SDL_Keycode = Sint32;
#[repr(u32)]
#[derive(Copy,Clone)]
pub enum SDL_BlendMode{
NONE = 0x00000000,
BLEND... | {
_mem: [u8; 0]
}
#[repr(C)]
pub struct SDL_Texture {
_mem: [u8; 0]
}
#[repr(C)]
pub struct SDL_Rect {
pub x: c_int, pub y: c_int,
pub w: c_int, pub h: c_int
}
#[link(name = "SDL2")]
extern "C" {
// SDL_video.h
pub fn SDL_CreateWindow(
title: *const c_char,
x: c_int, y: c_int... | SDL_Renderer | identifier_name |
build.rs | // Copyright 2021 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.
use std::env;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
println!("cargo:rustc-cf... | Ok(())
}
fn rustc_minor_version() -> Option<u32> {
let rustc = match env::var_os("RUSTC") {
Some(rustc) => rustc,
None => return None,
};
let output = match Command::new(rustc).arg("--version").output() {
Ok(output) => output,
Err(_) => return None,
};
let vers... | let mut file = std::fs::File::create(output_dir.join("generated.rs"))?;
file.write_all(b"fn run_some_generated_code() -> u32 { 42 }")?; | random_line_split |
build.rs | // Copyright 2021 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.
use std::env;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
println!("cargo:rustc-cf... |
let next = match pieces.next() {
Some(next) => next,
None => return None,
};
u32::from_str(next).ok()
}
| {
let rustc = match env::var_os("RUSTC") {
Some(rustc) => rustc,
None => return None,
};
let output = match Command::new(rustc).arg("--version").output() {
Ok(output) => output,
Err(_) => return None,
};
let version = match str::from_utf8(&output.stdout) {
O... | identifier_body |
build.rs | // Copyright 2021 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.
use std::env;
use std::io::Write;
use std::path::Path;
use std::process::Command;
use std::str::{self, FromStr};
fn | () {
println!("cargo:rustc-cfg=build_script_ran");
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
let target = env::var("TARGET").unwrap();
if minor >= 34 {
println!("cargo:rustc-cfg=is_new_rustc");
} else {
println!("cargo:ru... | main | identifier_name |
update.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_package: Option<String>,
flag_aggressive: bool,
flag_precise: Option<String>,
flag_manifest_path: Option<String>,
... | (options: Options, config: &Config) -> CliResult<Option<()>> {
debug!("executing; cmd=cargo-update; args={:?}", env::args().collect::<Vec<_>>());
config.shell().set_verbose(options.flag_verbose);
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let spec = options.flag_package.as... | execute | identifier_name |
update.rs | use std::env;
use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_package: Option<String>,
flag_aggressive: bool,
flag_precise: Option<String>,
flag_manifest_path: Option<String>,
... |
If SPEC is given, then a conservative update of the lockfile will be
performed. This means that only the dependency specified by SPEC will be
updated. Its transitive dependencies will be updated only if SPEC cannot be
updated without updating dependencies. All other dependencies will remain
locked at their currently ... | --manifest-path PATH Path to the manifest to compile
-v, --verbose Use verbose output
This command requires that a `Cargo.lock` already exists as generated by
`cargo build` or related commands. | random_line_split |
mod.rs | use super::Path;
use super::connector::Connector;
use super::resolver::Resolve;
use futures::{Async, Future, Poll, unsync};
use ordermap::OrderMap;
use std::{cmp, io, net};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tacho;
use tokio_core::reactor::Handle;
use tokio_timer::Timer;
mod dispat... |
}
pub fn new(
reactor: &Handle,
timer: &Timer,
dst: &Path,
connector: Connector,
resolve: Resolve,
metrics: &tacho::Scope,
) -> Balancer {
let (tx, rx) = unsync::mpsc::unbounded();
let dispatcher = dispatcher::new(
reactor.clone(),
timer.clone(),
dst.clone(),
... | {
WeightedAddr { addr, weight }
} | identifier_body |
mod.rs | use super::Path;
use super::connector::Connector;
use super::resolver::Resolve;
use futures::{Async, Future, Poll, unsync};
use ordermap::OrderMap;
use std::{cmp, io, net};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tacho;
use tokio_core::reactor::Handle;
use tokio_timer::Timer;
mod dispat... | (unsync::mpsc::UnboundedSender<Waiter>);
impl Balancer {
/// Obtains a connection to the destination.
pub fn connect(&self) -> Connect {
let (tx, rx) = unsync::oneshot::channel();
let result = unsync::mpsc::UnboundedSender::unbounded_send(&self.0, tx)
.map_err(|_| io::Error::new(io::E... | Balancer | identifier_name |
mod.rs | use super::Path;
use super::connector::Connector;
use super::resolver::Resolve;
use futures::{Async, Future, Poll, unsync};
use ordermap::OrderMap;
use std::{cmp, io, net};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use tacho;
use tokio_core::reactor::Handle;
use tokio_timer::Timer;
mod dispat... | }
#[derive(Clone)]
pub struct Balancer(unsync::mpsc::UnboundedSender<Waiter>);
impl Balancer {
/// Obtains a connection to the destination.
pub fn connect(&self) -> Connect {
let (tx, rx) = unsync::oneshot::channel();
let result = unsync::mpsc::UnboundedSender::unbounded_send(&self.0, tx)
... | Endpoints::default(),
metrics,
);
reactor.spawn(dispatcher.map_err(|_| {}));
Balancer(tx) | random_line_split |
callee.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let llfn = if let Some(llfn) = cx.get_declared_value(&sym) {
// This is subtle and surprising, but sometimes we have to bitcast
// the resulting fn pointer. The reason has to do with external
// functions. If you have two crates that both bind the same C
// library, they may not u... | {
let tcx = cx.tcx();
debug!("get_fn(instance={:?})", instance);
assert!(!instance.substs.needs_infer());
assert!(!instance.substs.has_escaping_bound_vars());
assert!(!instance.substs.has_param_types());
let sig = instance.fn_sig(cx.tcx());
if let Some(&llfn) = cx.instances().borrow().get... | identifier_body |
callee.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 ... | } else {
debug!("get_fn: not casting pointer!");
llfn
}
} else {
let llfn = cx.declare_fn(&sym, sig);
assert_eq!(cx.val_ty(llfn), llptrty);
debug!("get_fn: not casting pointer!");
if instance.def.is_inline(tcx) {
attributes::inline... | // reference. It also occurs when testing libcore and in some
// other weird situations. Annoying.
if cx.val_ty(llfn) != llptrty {
debug!("get_fn: casting {:?} to {:?}", llfn, llptrty);
cx.const_ptrcast(llfn, llptrty) | random_line_split |
callee.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 ... |
}
}
}
if cx.use_dll_storage_attrs &&
tcx.is_dllimport_foreign_item(instance_def_id)
{
unsafe {
llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport);
}
}
llfn
};
cx.instance... | {
// This is a function from an upstream crate that has
// been instantiated here. These are always hidden.
llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
} | conditional_block |
callee.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 ... | (
cx: &CodegenCx<'ll, 'tcx>,
instance: Instance<'tcx>,
) -> &'ll Value {
let tcx = cx.tcx();
debug!("get_fn(instance={:?})", instance);
assert!(!instance.substs.needs_infer());
assert!(!instance.substs.has_escaping_bound_vars());
assert!(!instance.substs.has_param_types());
let sig = ... | get_fn | identifier_name |
macro-comma-behavior.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 ... | }
unimplemented!("{}",);
//[core]~^ ERROR no arguments
//[std]~^^ ERROR no arguments
// if falsum() { unreachable!("{}",); } // see run-pass
struct S;
impl fmt::Display for S {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}",)?;
//[cor... | // FIXME: compile-fail says "expected error not found" even though
// rustc does emit an error
// println!("{}",);
// <DISABLED> [std]~^ ERROR no arguments | random_line_split |
macro-comma-behavior.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 ... | {} | identifier_body | |
macro-comma-behavior.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 ... | ;
impl fmt::Display for S {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}",)?;
//[core]~^ ERROR no arguments
//[std]~^^ ERROR no arguments
// FIXME: compile-fail says "expected error not found" even though
// rustc do... | S | identifier_name |
main.rs | /*
Rust - Std Misc Path
Licence : GNU GPL v3 or later
Author : AurΓ©lien DESBRIΓRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ββββββββββββββββ
Rust ββββββββββββββββββββββββββββββββ
*/
use std::path::Path;
fn main() {
// Create a `Path` from a `&'static str`
... | // windows::Path | // posix::Path | random_line_split |
main.rs | /*
Rust - Std Misc Path
Licence : GNU GPL v3 or later
Author : AurΓ©lien DESBRIΓRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ββββββββββββββββ
Rust ββββββββββββββββββββββββββββββββ
*/
use std::path::Path;
fn main() {
// Create a `Path` from a `&'static str`
... | ` method returns a `Show`able structure
//let display = path.display();
println!("{}", path.display());
// `join` merges a path with a byte container using the OS specific
// separator, and returns the new path
let new_path = path.join("a").join("b");
// Convert the path into a string slice
... | identifier_body | |
main.rs | /*
Rust - Std Misc Path
Licence : GNU GPL v3 or later
Author : AurΓ©lien DESBRIΓRES
Mail : aurelien(at)hackers(dot)camp
Created on : June 2017
Write with Emacs-nox ββββββββββββββββ
Rust ββββββββββββββββββββββββββββββββ
*/
use std::path::Path;
fn main() {
// Create a `Path` from a `&'static str`
... | lay` method returns a `Show`able structure
//let display = path.display();
println!("{}", path.display());
// `join` merges a path with a byte container using the OS specific
// separator, and returns the new path
let new_path = path.join("a").join("b");
// Convert the path into a string slice... | disp | identifier_name |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... | () {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format!("{}/", out_di... | main | identifier_name |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... |
fn main() {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format!("{}/... | {
if cfg!(target_os = "freebsd") {"gmake"} else {"make"}
} | identifier_body |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... | let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format!("{}/", out_dir)));
println!("cargo:rustc-link-search=native={}", out_dir)... | if cfg!(target_os = "freebsd") {"gmake"} else {"make"}
}
fn main() {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); | random_line_split |
build.rs | // build.rs
use std::process::Command;
use std::env;
macro_rules! t {
($e:expr) => (match $e {
Ok(t) => t,
Err(e) => panic!("{} return the error {}", stringify!($e), e),
})
}
fn run(cmd: &mut Command) {
println!("running: {:?}", cmd);
assert!(t!(cmd.status()).success());
}
fn make() ... |
}
fn main() {
let proj_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = env::var("OUT_DIR").unwrap();
run(Command::new(make())
.arg("-j4")
.current_dir("3rdparty/FreeImage"));
run(Command::new("cp")
.arg("3rdparty/FreeImage/Dist/libfreeimage.a")
.arg(format!("{... | {"make"} | conditional_block |
delete.rs | // Copyright (c) 2016-2018 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | .map_err(Error::DepotClient)?;
ui.status(Status::Deleted, format!("secret {}.", key))?;
Ok(())
} | depot_client
.delete_origin_secret(origin, token, key) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.