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
formatter.rs
use std::str; use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
/// precision getter pub fn precision(&self) -> Option<usize> { self.precision } /// set precision to None, used for formatting int, float, etc pub fn set_precision(&mut self, precision: Option<usize>) { self.precision = precision; } /// sign getter pub fn sign(&self)...
{ self.thousands }
identifier_body
formatter.rs
use std::str; use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
c = match chars.next() { Some(c) => c, None => { break; } }; } let (identifier, rest) = s.split_at(consumed); let identifier = if found_colon { let (i, _) = identifier.split_at(identifier.len...
{ found_colon = true; break; }
conditional_block
formatter.rs
use std::str; use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
return Err(FmtError::Invalid("overflow error when parsing precision" .to_string())) } Some(v) => { format.precision = v; } } } else { // Not having ...
let (consumed, val) = get_integer(rest, pos); if consumed != 0 { match val { None => {
random_line_split
formatter.rs
use std::str; use std::fmt; use std::fmt::Write; use std::iter::Iterator; use std::string::String; use types::*; #[derive(Debug, PartialEq)] pub struct Formatter<'a, 'b> { pub key: &'a str, fill: char, align: Alignment, // default Right for numbers, Left for strings sign: Sign, alternate: bool, ...
(s: &'a str, buff: &'b mut String) -> Result<Formatter<'a, 'b>> { let mut found_colon = false; let mut chars = s.chars(); let mut c = match chars.next() { Some(':') | None => { return Err(FmtError::Invalid("must specify identifier".to_string())) } ...
from_str
identifier_name
join.rs
use std::fmt; use std::str; use column::Column; use condition::ConditionExpression; use nom::branch::alt; use nom::bytes::complete::tag_no_case; use nom::combinator::map; use nom::IResult; use select::{JoinClause, SelectStatement}; use table::Table; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]...
{ /// A single table. Table(Table), /// A comma-separated (and implicitly joined) sequence of tables. Tables(Vec<Table>), /// A nested selection, represented as (query, alias). NestedSelect(Box<SelectStatement>, Option<String>), /// A nested join clause. NestedJoin(Box<JoinClause>), } ...
JoinRightSide
identifier_name
join.rs
use std::fmt; use std::str; use column::Column; use condition::ConditionExpression; use nom::branch::alt; use nom::bytes::complete::tag_no_case; use nom::combinator::map; use nom::IResult; use select::{JoinClause, SelectStatement}; use table::Table; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]...
..Default::default() }; let q = res.unwrap().1; assert_eq!(q, expected_stmt); assert_eq!(qstring, format!("{}", q)); } }
{ let qstring = "SELECT tags.* FROM tags \ INNER JOIN taggings ON tags.id = taggings.tag_id"; let res = selection(qstring.as_bytes()); let ct = ConditionTree { left: Box::new(Base(Field(Column::from("tags.id")))), right: Box::new(Base(Field(Column...
identifier_body
join.rs
use std::fmt; use std::str; use column::Column; use condition::ConditionExpression; use nom::branch::alt; use nom::bytes::complete::tag_no_case; use nom::combinator::map; use nom::IResult; use select::{JoinClause, SelectStatement}; use table::Table; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]...
} }
let q = res.unwrap().1; assert_eq!(q, expected_stmt); assert_eq!(qstring, format!("{}", q));
random_line_split
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
// XXX: Figure out how to move self into the closure to // get rid of the.clone. fn add_to(self, e: Entity) { world::with_mut(|w| w.$access_mut().insert(e, self.clone())) } } )+ // Implement the trait for accessing all the components that ...
impl Component for $comp {
random_line_split
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
let ret = Entity(*idx); *idx += 1; if!w.ecs.active[*idx - 1] { continue; } return Some(ret); } }) } } //////////////////////////////////////////////////////////////////////// // The one big macro for defining the full set of avai...
{ return None; }
conditional_block
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
(&mut self) -> Option<Entity> { world::with(|w| { let &mut EntityIter(ref mut idx) = self; loop { if *idx >= w.ecs.active.len() { return None; } let ret = Entity(*idx); *idx += 1; if!w.ecs.active[*idx - 1] { continue; } ...
next
identifier_name
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
} pub struct EntityIter(usize); impl Iterator for EntityIter { type Item = Entity; fn next(&mut self) -> Option<Entity> { world::with(|w| { let &mut EntityIter(ref mut idx) = self; loop { if *idx >= w.ecs.active.len() { return None; } let ret = ...
{ self.parent.insert(idx, new_parent_idx); }
identifier_body
message_log.rs
use std::{env, process::exit, time::Duration}; use assign::assign; use ruma::{ api::client::{filter::FilterDefinition, sync::sync_events}, events::{ room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, AnySyncMessageLikeEvent, AnySyncRoomEvent, SyncMessageLikeEvent, ...
while let Some(res) = sync_stream.try_next().await? { // Only look at rooms the user hasn't left yet for (room_id, room) in res.rooms.join { for event in room.timeline.events.into_iter().flat_map(|r| r.deserialize()) { // Filter out the text messages if le...
{ let client = ruma::Client::builder().homeserver_url(homeserver_url).build::<HttpClient>().await?; client.log_in(username, password, None, None).await?; let filter = FilterDefinition::ignore_all().into(); let initial_sync_response = client .send_request(assign!(sync_events::v3::Reques...
identifier_body
message_log.rs
use std::{env, process::exit, time::Duration}; use assign::assign; use ruma::{ api::client::{filter::FilterDefinition, sync::sync_events}, events::{ room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, AnySyncMessageLikeEvent, AnySyncRoomEvent, SyncMessageLikeEvent, ...
&PresenceState::Online, Some(Duration::from_secs(30)), )); while let Some(res) = sync_stream.try_next().await? { // Only look at rooms the user hasn't left yet for (room_id, room) in res.rooms.join { for event in room.timeline.events.into_iter().flat_map(|r| r.deseri...
.await?; let mut sync_stream = Box::pin(client.sync( None, initial_sync_response.next_batch,
random_line_split
message_log.rs
use std::{env, process::exit, time::Duration}; use assign::assign; use ruma::{ api::client::{filter::FilterDefinition, sync::sync_events}, events::{ room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, AnySyncMessageLikeEvent, AnySyncRoomEvent, SyncMessageLikeEvent, ...
( homeserver_url: String, username: &str, password: &str, ) -> anyhow::Result<()> { let client = ruma::Client::builder().homeserver_url(homeserver_url).build::<HttpClient>().await?; client.log_in(username, password, None, None).await?; let filter = FilterDefinition::ignore_all().into()...
log_messages
identifier_name
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
} self.counts.borrow_mut().insert(patch.meta.patch_id, count); } } true } fn check_connect(&self, req: &Request) -> bool { let h_ptr = req.type_header.as_ptr() as *const usbr::ConnectHeader; let h: &usbr::ConnectHeader = unsafe {...
{ for patch in &self.patches { if patch.meta.p_type != "bulk" { continue; } // The metadata matches, time to compare the data let data_hex: String = req.data[..].to_hex(); if data_hex.len() >= patch.data.len() && data_hex.contains(&...
identifier_body
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
// The metadata matches, time to compare the data let data_hex: String = req.data[..].to_hex(); if data_hex.len() >= patch.data.len() && data_hex.contains(&patch.data) { let mut count: u16 = *self.counts.borrow().get(&patch.meta.patch_id).unwrap(); ...
{ continue; }
conditional_block
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
fn handle_connect(&self, _: Source, req: Request) -> (u8, Vec<Request>) { if self.check_connect(&req) { (0, vec![req]) } else { (1, vec![req]) } } // TODO: Implement below // // fn handle_int_packet(&self, source: Source, req: Request) -> (u8, Vec<Request>) { // (0, vec![req]) // }...
fn handle_bulk_packet(&self, _: Source, req: Request) -> (u8, Vec<Request>) { if self.check_bulk_packet(&req) { (0, vec![req]) } else { (1, vec![req]) } }
random_line_split
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
(&self, req: &Request) -> bool { for patch in &self.patches { if patch.meta.p_type!= "bulk" { continue; } // The metadata matches, time to compare the data let data_hex: String = req.data[..].to_hex(); if data_hex.len() >= patch.dat...
check_bulk_packet
identifier_name
log.rs
//! Logger implementation use std::fs::File; use std::io::Write; use std::fs::OpenOptions; use std::path::PathBuf; use std::collections::HashMap; use std::sync::{Mutex, MutexGuard}; use std::borrow::Borrow; use std; /// Logger category. Logger can be configured to save /// messages of each category to a separate file...
/// Returns false if messages of `category` are ignored. This function /// can be used to skip expensive construction of messages. pub fn is_on(&self, category: LoggerCategory) -> bool { self.settings(category).is_on() } /// Lazy-log. If messages of `category` are not ignored, calls the passed closure ...
{ self.category_settings = value; self.files.clear(); }
identifier_body
log.rs
//! Logger implementation use std::fs::File; use std::io::Write; use std::fs::OpenOptions; use std::path::PathBuf; use std::collections::HashMap; use std::sync::{Mutex, MutexGuard}; use std::borrow::Borrow; use std; /// Logger category. Logger can be configured to save /// messages of each category to a separate file...
} /// Log a message `text` to `category`. pub fn log<T: Borrow<str>>(&mut self, category: LoggerCategory, text: T) { self.llog(category, move || text); } /// Returns settings for `category`. fn settings(&self, category: LoggerCategory) -> &LoggerSettings { if let Some(data) = self.category_settin...
{ if !self.files.contains_key(&category) { let file = OpenOptions::new() .write(true) .create(true) .append(true) .open(path) .unwrap_or_else(|err| panic!("failed to open log file '{}': {}", path.display(), err)); self.files.ins...
conditional_block
log.rs
//! Logger implementation use std::fs::File; use std::io::Write; use std::fs::OpenOptions; use std::path::PathBuf; use std::collections::HashMap; use std::sync::{Mutex, MutexGuard}; use std::borrow::Borrow; use std; /// Logger category. Logger can be configured to save /// messages of each category to a separate file...
default_logger().llog(category, f); } /// Convenience method to check if `category` is enabled in the default logger. pub fn is_on(category: LoggerCategory) -> bool { default_logger().is_on(category) }
pub fn llog<T: Borrow<str>, F: FnOnce() -> T>(category: LoggerCategory, f: F) {
random_line_split
log.rs
//! Logger implementation use std::fs::File; use std::io::Write; use std::fs::OpenOptions; use std::path::PathBuf; use std::collections::HashMap; use std::sync::{Mutex, MutexGuard}; use std::borrow::Borrow; use std; /// Logger category. Logger can be configured to save /// messages of each category to a separate file...
<T: Borrow<str>>(category: LoggerCategory, text: T) { default_logger().log(category, text); } /// Convenience method to lazy-log messages to the default logger and specified `category`. /// If messages of `category` are not ignored, calls the passed closure /// and uses its output value as a message in that category...
log
identifier_name
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataLi...
} impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> DomRoot<HTMLCollection> { #[derive(JSTraceable, MallocSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOption...
{ Node::reflect_node( Box::new(HTMLDataListElement::new_inherited( local_name, prefix, document, )), document, HTMLDataListElementBinding::Wrap, ) }
identifier_body
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement...
* License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
random_line_split
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataLi...
(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = Box::new(HTMLDataListOptionsFilter); let window = window_from_node(self); HTMLCollection::create(&window, self.upcast(), filter) } }
filter
identifier_name
hr.rs
use regex::Regex; use parser::Block; use parser::Block::Hr; pub fn parse_hr(lines: &[&str]) -> Option<(Block, usize)> { let HORIZONTAL_RULE = Regex::new(r"^(===+)$|^(---+)$").unwrap(); if HORIZONTAL_RULE.is_match(lines[0]){ return Some((Hr, 1)); } return None; } #[cfg(test)] mod test { us...
}
{ assert_eq!(parse_hr(&vec!["a-------"]), None); assert_eq!(parse_hr(&vec!["--- a"]), None); assert_eq!(parse_hr(&vec!["--a-"]), None); assert_eq!(parse_hr(&vec!["-------====--------------"]), None); assert_eq!(parse_hr(&vec!["a======"]), None); assert_eq!(parse_hr(&vec!...
identifier_body
hr.rs
use regex::Regex; use parser::Block; use parser::Block::Hr; pub fn parse_hr(lines: &[&str]) -> Option<(Block, usize)> { let HORIZONTAL_RULE = Regex::new(r"^(===+)$|^(---+)$").unwrap();
return Some((Hr, 1)); } return None; } #[cfg(test)] mod test { use super::parse_hr; use parser::Block::Hr; #[test] fn finds_hr() { assert_eq!(parse_hr(&vec!["-------"]).unwrap(), (Hr, 1)); assert_eq!(parse_hr(&vec!["---"]).unwrap(), (Hr, 1)); assert_eq!(parse_hr...
if HORIZONTAL_RULE.is_match(lines[0]){
random_line_split
hr.rs
use regex::Regex; use parser::Block; use parser::Block::Hr; pub fn parse_hr(lines: &[&str]) -> Option<(Block, usize)> { let HORIZONTAL_RULE = Regex::new(r"^(===+)$|^(---+)$").unwrap(); if HORIZONTAL_RULE.is_match(lines[0]){ return Some((Hr, 1)); } return None; } #[cfg(test)] mod test { us...
() { assert_eq!(parse_hr(&vec!["a-------"]), None); assert_eq!(parse_hr(&vec!["--- a"]), None); assert_eq!(parse_hr(&vec!["--a-"]), None); assert_eq!(parse_hr(&vec!["-------====--------------"]), None); assert_eq!(parse_hr(&vec!["a======"]), None); assert_eq!(parse_hr(&v...
no_false_positives
identifier_name
hr.rs
use regex::Regex; use parser::Block; use parser::Block::Hr; pub fn parse_hr(lines: &[&str]) -> Option<(Block, usize)> { let HORIZONTAL_RULE = Regex::new(r"^(===+)$|^(---+)$").unwrap(); if HORIZONTAL_RULE.is_match(lines[0])
return None; } #[cfg(test)] mod test { use super::parse_hr; use parser::Block::Hr; #[test] fn finds_hr() { assert_eq!(parse_hr(&vec!["-------"]).unwrap(), (Hr, 1)); assert_eq!(parse_hr(&vec!["---"]).unwrap(), (Hr, 1)); assert_eq!(parse_hr(&vec!["---------------------------...
{ return Some((Hr, 1)); }
conditional_block
mod.rs
use core::creature::Creature; use core::renderer::{Renderable, RGB}; use core::time::Time; use core::world::dungeon::map::{self, Pos, Tile}; #[derive(Clone)] pub enum Money { Copper, Silver, Electrum, Gold, Quartz, Platinum, Mithril, Scale, Onyx, Tourmaline, Emerald, Ruby, Sapphire, Topaz,...
} /// /// Implement the `Renderable` trait for `Item`, mostly just getters and setters /// impl Renderable for Item { #[inline] fn get_bg(&self) -> RGB { self.bg } #[inline] fn get_fg(&self) -> RGB { self.fg } #[inline] fn get_glyph(&self) -> char { self.glyph } #[inline] fn get_...
{ Item { name, glyph, pos, fg, bg, quantity, property } }
identifier_body
mod.rs
use core::creature::Creature; use core::renderer::{Renderable, RGB}; use core::time::Time; use core::world::dungeon::map::{self, Pos, Tile}; #[derive(Clone)] pub enum Money { Copper, Silver, Electrum, Gold, Quartz, Platinum, Mithril, Scale, Onyx, Tourmaline, Emerald, Ruby, Sapphire, Topaz, ...
self.glyph = glyph } #[inline] fn set_id(&mut self, name: &'static str) { self.name = name; } } impl Time for Item { fn take_turn(&mut self, _map: &map::Grid<Tile>, _player: &Creature) { } }
#[inline] fn set_glyph(&mut self, glyph: char) {
random_line_split
mod.rs
use core::creature::Creature; use core::renderer::{Renderable, RGB}; use core::time::Time; use core::world::dungeon::map::{self, Pos, Tile}; #[derive(Clone)] pub enum
{ Copper, Silver, Electrum, Gold, Quartz, Platinum, Mithril, Scale, Onyx, Tourmaline, Emerald, Ruby, Sapphire, Topaz, Diamond, } pub fn money_value(money: &Money) -> f32 { match money { Money::Copper => 0.01, Money::Silver => 0.1, Money::Electrum => 0.5, Money::Gold | M...
Money
identifier_name
propagate-approximated-shorter-to-static-no-bound.rs
// Test a case where we are trying to prove `'x: 'y` and are forced to // approximate the shorter end-point (`'y`) to with `'static`. This is // because `'y` is higher-ranked but we know of no relations to other // regions. Note that `'static` shows up in the stderr output as `'0`. // compile-flags:-Zborrowck=mir -Zve...
where F: for<'x, 'y> FnMut( &Cell<&'a &'x u32>, // shows that 'x: 'a &Cell<&'x u32>, &Cell<&'y u32>, ), { } fn demand_y<'x, 'y>(_cell_x: &Cell<&'x u32>, _cell_y: &Cell<&'y u32>, _y: &'y u32) {} #[rustc_regions] fn supply<'a, 'b>(cell_a: Cell<&'a u32>, cell_b: Cell<&'b u32>) { estab...
fn establish_relationships<'a, 'b, F>(_cell_a: &Cell<&'a u32>, _cell_b: &Cell<&'b u32>, _closure: F)
random_line_split
propagate-approximated-shorter-to-static-no-bound.rs
// Test a case where we are trying to prove `'x: 'y` and are forced to // approximate the shorter end-point (`'y`) to with `'static`. This is // because `'y` is higher-ranked but we know of no relations to other // regions. Note that `'static` shows up in the stderr output as `'0`. // compile-flags:-Zborrowck=mir -Zve...
<'a, 'b>(cell_a: Cell<&'a u32>, cell_b: Cell<&'b u32>) { establish_relationships(&cell_a, &cell_b, |_outlives, x, y| { //~^ ERROR borrowed data escapes outside of function // Only works if 'x: 'y: demand_y(x, y, x.get()) }); } fn main() {}
supply
identifier_name
propagate-approximated-shorter-to-static-no-bound.rs
// Test a case where we are trying to prove `'x: 'y` and are forced to // approximate the shorter end-point (`'y`) to with `'static`. This is // because `'y` is higher-ranked but we know of no relations to other // regions. Note that `'static` shows up in the stderr output as `'0`. // compile-flags:-Zborrowck=mir -Zve...
#[rustc_regions] fn supply<'a, 'b>(cell_a: Cell<&'a u32>, cell_b: Cell<&'b u32>) { establish_relationships(&cell_a, &cell_b, |_outlives, x, y| { //~^ ERROR borrowed data escapes outside of function // Only works if 'x: 'y: demand_y(x, y, x.get()) }); } fn main() {}
{}
identifier_body
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; let _t = range(0u, n).map(|i| { expected += i; let tx = tx.clone(); Thread::scoped(move|| { child(&tx, i) }) }).collect::<Vec<_>>(); let mut actual = 0u; for _ in range(0u, n) { ...
identifier_body
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(tx: &Sender<Box<uint>>, i: uint) { tx.send(box i).unwrap(); } pub fn main() { let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; let _t = range(0u, n).map(|i| { expected += i; let tx = tx.clone(); Thread::scoped(move|| { child(&tx, i) }) ...
child
identifier_name
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use std::thread::Thread; fn child(tx: &Sender<Box<uint>>, i: uint) { tx.send(box i).unwrap(); } pub fn main() { let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; let _t = range(0u, n).map(|i| { expected += i; let tx = tx.clone(); Thread::scoped(move|| { ...
#![allow(unknown_features)] #![feature(box_syntax)] use std::sync::mpsc::{channel, Sender};
random_line_split
chordangle.rs
/* Copyright 2015 Google Inc. All rights reserved. Copyright 2017 Jihyun Yu. All rights reserved. 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...
#[test] fn test_chordangle_basics() { let zero = ChordAngle::default(); test_chordangle_basics_case(NEGATIVE, NEGATIVE, false, true); test_chordangle_basics_case(NEGATIVE, zero, true, false); test_chordangle_basics_case(NEGATIVE, STRAIGHT, true, false); test_chordangle_bas...
assert_eq!(less_than, ca1 < ca2); assert_eq!(equal, ca1 == ca2); }
identifier_body
chordangle.rs
/* Copyright 2015 Google Inc. All rights reserved. Copyright 2017 Jihyun Yu. All rights reserved. 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...
Deg) -> Self { Angle::from(&a).into() } } impl<'a> From<&'a ChordAngle> for Angle { /// converts this ChordAngle to an Angle. fn from(ca: &'a ChordAngle) -> Self { if ca.0 < 0. { Rad(-1.).into() } else if ca.is_infinite() { Angle::inf() } else { ...
(a:
identifier_name
chordangle.rs
/* Copyright 2015 Google Inc. All rights reserved. Copyright 2017 Jihyun Yu. All rights reserved. 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...
Angle::from(&a).into() } } impl<'a> From<&'a ChordAngle> for Angle { /// converts this ChordAngle to an Angle. fn from(ca: &'a ChordAngle) -> Self { if ca.0 < 0. { Rad(-1.).into() } else if ca.is_infinite() { Angle::inf() } else { Rad(2. *...
fn from(a: Deg) -> Self {
random_line_split
chordangle.rs
/* Copyright 2015 Google Inc. All rights reserved. Copyright 2017 Jihyun Yu. All rights reserved. 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...
e if a.is_infinite() { ChordAngle::inf() } else { let l = 2. * (0.5 * a.rad().min(PI)).sin(); ChordAngle(l * l) } } } impl From<Angle> for ChordAngle { /// returns a ChordAngle from the given Angle. fn from(a: Angle) -> Self { ChordAngle::from(&a) ...
NEGATIVE } els
conditional_block
action_batcher.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
self.actions.insert(entity_id, Vec::new()); } self.actions.get_mut(&entity_id).unwrap().push(action); } pub fn consume_actions(&mut self) -> HashMap<Index, Vec<Action>> { let mut consumed = HashMap::new(); mem::swap(&mut consumed, &mut self.actions); consumed...
if !self.actions.contains_key(&entity_id) {
random_line_split
action_batcher.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
{ actions: HashMap<Index, Vec<Action>>, } impl ActionBatcher { pub fn new() -> ActionBatcher { ActionBatcher { actions: HashMap::new() } } pub fn queue_for_entity(&mut self, entity_id: Index, action: Action) { if!self.actions.contains_key(&entity_id) { self.actions.insert(...
ActionBatcher
identifier_name
action_batcher.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
self.actions.get_mut(&entity_id).unwrap().push(action); } pub fn consume_actions(&mut self) -> HashMap<Index, Vec<Action>> { let mut consumed = HashMap::new(); mem::swap(&mut consumed, &mut self.actions); consumed } }
{ self.actions.insert(entity_id, Vec::new()); }
conditional_block
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
{ pub headers: Option<Headers>, pub status: Option<RawStatus>, pub body: Option<Vec<u8>>, pub pipeline_id: PipelineId, } pub enum NetworkEvent { HttpRequest(HttpRequest), HttpResponse(HttpResponse), } impl TimelineMarker { pub fn start(name: String) -> StartedTimelineMarker { Star...
HttpResponse
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
GetDocumentElement(PipelineId, IpcSender<NodeInfo>), /// Retrieve the details of the child nodes of the given node in the given pipeline. GetChildren(PipelineId, String, IpcSender<Vec<NodeInfo>>), /// Retrieve the computed layout properties of the given node in the given pipeline. GetLayout(Pipeline...
random_line_split
mod.rs
use crate::debug_protocol::Expressions; #[macro_use] pub mod prelude { use nom::{ character::complete::{digit1, space0}, error::ParseError, sequence::delimited, IResult, }; pub type Span<'a> = &'a str; pub fn ws<'a, F: 'a, O, E: ParseError<Span<'a>>>(parser: F) -> impl ...
#[derive(Debug)] pub enum PreparedExpression { Native(String), Simple(String), Python(String), } // Parse expression type and preprocess it. pub fn prepare(expression: &str, default_type: Expressions) -> PreparedExpression { let (expr, ty) = get_expression_type(expression, default_type); match ty {...
random_line_split
mod.rs
use crate::debug_protocol::Expressions; #[macro_use] pub mod prelude { use nom::{ character::complete::{digit1, space0}, error::ParseError, sequence::delimited, IResult, }; pub type Span<'a> = &'a str; pub fn ws<'a, F: 'a, O, E: ParseError<Span<'a>>>(parser: F) -> impl ...
<'a>(expr: &'a str, default_type: Expressions) -> (&'a str, Expressions) { if expr.starts_with("/nat ") { (&expr[5..], Expressions::Native) } else if expr.starts_with("/py ") { (&expr[4..], Expressions::Python) } else if expr.starts_with("/se ") { (&expr[4..], Expressions::Simple) ...
get_expression_type
identifier_name
file.rs
use std::fs::{File, create_dir_all}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use walkdir::WalkDir; use error::{Error, Result}; pub fn read_file<T: AsRef<Path>>(path: T) -> Result<Vec<u8>> { let mut file = File::open(path)?; let file_len = file.metadata()?.len(); let mut buf = Vec::wit...
result.push((path.to_owned(), file)); } } Ok(result) } pub fn write_file(path: &Path, content: &[u8]) -> Result<()> { create_dir_all(path.to_owned().parent().ok_or(Error::DirNotFound)?)?; let mut file = File::create(path)?; file.write_all(content)?; Ok(()) }
let path = entry.path(); if path.is_file() { let file = read_file(path)?; let path = path.strip_prefix(&root)?;
random_line_split
file.rs
use std::fs::{File, create_dir_all}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use walkdir::WalkDir; use error::{Error, Result}; pub fn
<T: AsRef<Path>>(path: T) -> Result<Vec<u8>> { let mut file = File::open(path)?; let file_len = file.metadata()?.len(); let mut buf = Vec::with_capacity(file_len as usize + 1); file.read_to_end(&mut buf)?; Ok(buf) } pub fn read_all_files<T: AsRef<Path>>(root: T) -> Result<Vec<(PathBuf, Vec<u8>)>> {...
read_file
identifier_name
file.rs
use std::fs::{File, create_dir_all}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use walkdir::WalkDir; use error::{Error, Result}; pub fn read_file<T: AsRef<Path>>(path: T) -> Result<Vec<u8>>
pub fn read_all_files<T: AsRef<Path>>(root: T) -> Result<Vec<(PathBuf, Vec<u8>)>> { let mut result = Vec::new(); for dir_entry in WalkDir::new(&root) { let entry = dir_entry?; let path = entry.path(); if path.is_file() { let file = read_file(path)?; let path = p...
{ let mut file = File::open(path)?; let file_len = file.metadata()?.len(); let mut buf = Vec::with_capacity(file_len as usize + 1); file.read_to_end(&mut buf)?; Ok(buf) }
identifier_body
file.rs
use std::fs::{File, create_dir_all}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use walkdir::WalkDir; use error::{Error, Result}; pub fn read_file<T: AsRef<Path>>(path: T) -> Result<Vec<u8>> { let mut file = File::open(path)?; let file_len = file.metadata()?.len(); let mut buf = Vec::wit...
} Ok(result) } pub fn write_file(path: &Path, content: &[u8]) -> Result<()> { create_dir_all(path.to_owned().parent().ok_or(Error::DirNotFound)?)?; let mut file = File::create(path)?; file.write_all(content)?; Ok(()) }
{ let file = read_file(path)?; let path = path.strip_prefix(&root)?; result.push((path.to_owned(), file)); }
conditional_block
gnss.rs
/* vim: set et ts=4 sw=4: */ /* gnss.rs * * Copyright (C) 2017 Pelagicore AB. * Copyright (C) 2017 Zeeshan Ali. * Copyright (C) 2020 Purism SPC. * * GPSShare 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 Foundat...
impl GNSS { pub fn new(config: Rc<Config>) -> io::Result<Self> { match config.dev_path { Some(ref path) => GNSS::new_for_path(path.as_path()), None => GNSS::new_detect(), } } fn new_for_path(path: &Path) -> io::Result<Self> { let port = File::open(path.as_os...
pub struct GNSS { reader: BufReader<fs::File>, }
random_line_split
gnss.rs
/* vim: set et ts=4 sw=4: */ /* gnss.rs * * Copyright (C) 2017 Pelagicore AB. * Copyright (C) 2017 Zeeshan Ali. * Copyright (C) 2020 Purism SPC. * * GPSShare 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 Foundat...
}
{ self.reader.read_line(buffer) }
identifier_body
gnss.rs
/* vim: set et ts=4 sw=4: */ /* gnss.rs * * Copyright (C) 2017 Pelagicore AB. * Copyright (C) 2017 Zeeshan Ali. * Copyright (C) 2020 Purism SPC. * * GPSShare 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 Foundat...
} false } } impl GPS for GNSS { fn read_line(&mut self, buffer: &mut String) -> io::Result<usize> { self.reader.read_line(buffer) } }
{ println!("Failed to read from serial port"); }
conditional_block
gnss.rs
/* vim: set et ts=4 sw=4: */ /* gnss.rs * * Copyright (C) 2017 Pelagicore AB. * Copyright (C) 2017 Zeeshan Ali. * Copyright (C) 2020 Purism SPC. * * GPSShare 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 Foundat...
(path: &Path) -> io::Result<Self> { let port = File::open(path.as_os_str())?; Ok(GNSS { reader: BufReader::new(port), }) } fn new_detect() -> io::Result<Self> { println!("Attempting to autodetect GNSS device..."); let context = libudev::Context::new()?; ...
new_for_path
identifier_name
sleeper_list.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
self.stack.with(|s| s.push(handle.take())); } } pub fn pop(&mut self) -> Option<SchedHandle> { unsafe { do self.stack.with |s| { if!s.is_empty() { Some(s.pop()) } else { None } ...
pub fn push(&mut self, handle: SchedHandle) { let handle = Cell::new(handle); unsafe {
random_line_split
sleeper_list.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } } } impl Clone for SleeperList { fn clone(&self) -> SleeperList { SleeperList { stack: self.stack.clone() } } }
{ None }
conditional_block
sleeper_list.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> SleeperList { SleeperList { stack: self.stack.clone() } } }
clone
identifier_name
sleeper_list.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn pop(&mut self) -> Option<SchedHandle> { unsafe { do self.stack.with |s| { if!s.is_empty() { Some(s.pop()) } else { None } } } } } impl Clone for SleeperList { fn clone(&s...
{ let handle = Cell::new(handle); unsafe { self.stack.with(|s| s.push(handle.take())); } }
identifier_body
render_thread.rs
use std::sync::mpsc::{Receiver, Sender}; use gfx; use glutin; use gfx_window_glutin; use std::collections::HashMap; use gfx::{Adapter, CommandQueue, Device, FrameSync, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx_device_gl; use image; use game::ContentId; use content::load_content::{EContentType, ...
RenderThread { _current_frame_index: 0, from_game_thread: from_game_thread, _to_content_manifest: to_content_manifest, _from_content_manifest: from_content_manifest, to_game_thread_with_input: to_game_thread_with_input, textures: HashMap::n...
random_line_split
render_thread.rs
use std::sync::mpsc::{Receiver, Sender}; use gfx; use glutin; use gfx_window_glutin; use std::collections::HashMap; use gfx::{Adapter, CommandQueue, Device, FrameSync, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx_device_gl; use image; use game::ContentId; use content::load_content::{EContentType,...
, _ => (), } } }); frame = swap_chain.acquire_frame(FrameSync::Semaphore(&frame_semaphore)); let frame_view = &views[frame.id()].clone(); frame_data = self.from_game_thread.try_recv(); let frame_data = matc...
{ // TODO }
conditional_block
render_thread.rs
use std::sync::mpsc::{Receiver, Sender}; use gfx; use glutin; use gfx_window_glutin; use std::collections::HashMap; use gfx::{Adapter, CommandQueue, Device, FrameSync, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx_device_gl; use image; use game::ContentId; use content::load_content::{EContentType,...
} #[derive(Clone)] pub struct RenderFrame { pub frame_index: u64, pub boxes: Option<Vec<BoxRenderData>>, pub spheres: Option<Vec<SphereRenderData>>, } impl RenderFrame { pub fn new(frame_index: u64, boxes: Option<Vec<BoxRenderData>>, spheres: Option<Vec<SphereRenderData>>) -> RenderFrame { Re...
{ RenderPackage { device, graphics_queue, frame_semaphore, draw_semaphore, frame_fence } }
identifier_body
render_thread.rs
use std::sync::mpsc::{Receiver, Sender}; use gfx; use glutin; use gfx_window_glutin; use std::collections::HashMap; use gfx::{Adapter, CommandQueue, Device, FrameSync, Surface, Swapchain, SwapchainExt, WindowExt}; use gfx_device_gl; use image; use game::ContentId; use content::load_content::{EContentType,...
{ pub frame_index: u64, pub boxes: Option<Vec<BoxRenderData>>, pub spheres: Option<Vec<SphereRenderData>>, } impl RenderFrame { pub fn new(frame_index: u64, boxes: Option<Vec<BoxRenderData>>, spheres: Option<Vec<SphereRenderData>>) -> RenderFrame { RenderFrame { frame_index: frame_...
RenderFrame
identifier_name
pointing.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_...
{ AutoCursor, SpecifiedCursor(Cursor), } impl ToCss for T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { T::AutoCursor => dest.write_str("auto"), T::SpecifiedCursor(c) =>...
T
identifier_name
pointing.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_...
computed_value::T::AutoCursor } pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { use std::ascii::AsciiExt; use style_traits::cursor::Cursor; let ident = try!(input.expect_ident()); if ident.eq_ignore_ascii_case("auto") { ...
#[inline] pub fn get_initial_value() -> computed_value::T {
random_line_split
pointing.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Pointing", inherited=True, gecko_...
} </%helpers:longhand> // NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact) // is nonstandard, slated for CSS4-UI. // TODO(pcwalton): SVG-only values. ${helpers.single_keyword("pointer-events", "auto none", animatable=False)} ${helpers.single_keyword("-moz-user-input", ...
{ Cursor::from_css_keyword(&ident) .map(SpecifiedValue::SpecifiedCursor) }
conditional_block
diagnostic.rs
call to `.bug` /// or `.span_bug` rather than a failed assertion, etc. #[derive(Copy)] pub struct ExplicitBug; /// A span-handler is like a handler but also /// accepts span information for source-location /// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, } impl SpanHand...
(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), Fatal | Error => "error".fmt(f), Warning => "warning".fmt(f), Note => "note".fmt(f), Help => "help".fmt(f), ...
fmt
identifier_name
diagnostic.rs
call to `.bug` /// or `.span_bug` rather than a failed assertion, etc. #[derive(Copy)] pub struct ExplicitBug; /// A span-handler is like a handler but also /// accepts span information for source-location /// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, } impl SpanHand...
pub fn span_unimpl(&self, sp: Span, msg: &str) ->! { self.span_bug(sp, &format!("unimplemented {}", msg)[]); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler } } /// A handler deals with errors; certain errors /// (fatal, bug, unimpl) may cause immediate exit, /// others l...
{ self.handler.emit(Some((&self.cm, sp)), msg, Bug); panic!(ExplicitBug); }
identifier_body
diagnostic.rs
explicit call to `.bug` /// or `.span_bug` rather than a failed assertion, etc. #[derive(Copy)] pub struct ExplicitBug; /// A span-handler is like a handler but also /// accepts span information for source-location /// reporting. pub struct SpanHandler { pub handler: Handler, pub cm: codemap::CodeMap, } impl...
// to a `LineBufferedWriter`, which means that emitting the reset // after the newline ends up buffering the reset until we print // another line or exit. Buffering the reset is a problem if we're // sharing the terminal with any other programs (e.g. other rustc ...
try!(t.attr(color)); // If `msg` ends in a newline, we need to reset the color before // the newline. We're making the assumption that we end up writing
random_line_split
any.rs
use AsLua; use AsMutLua; use Push; use PushGuard; use LuaRead; /// Represents any value that can be stored by Lua #[derive(Clone, Debug, PartialEq)] pub enum AnyLuaValue { LuaString(String), LuaNumber(f64), LuaBoolean(bool), LuaArray(Vec<(AnyLuaValue, AnyLuaValue)>), /// The "Other" element is (h...
let _lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(AnyLuaValue::LuaString(v)), Err(lua) => lua }; /*let _lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(AnyLuaValue::LuaArray(v)), Err(lua)...
random_line_split
any.rs
use AsLua; use AsMutLua; use Push; use PushGuard; use LuaRead; /// Represents any value that can be stored by Lua #[derive(Clone, Debug, PartialEq)] pub enum AnyLuaValue { LuaString(String), LuaNumber(f64), LuaBoolean(bool), LuaArray(Vec<(AnyLuaValue, AnyLuaValue)>), /// The "Other" element is (h...
(lua: L, index: i32) -> Result<AnyLuaValue, L> { let lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(AnyLuaValue::LuaNumber(v)), Err(lua) => lua }; let lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(Any...
lua_read_at_position
identifier_name
disk.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn create(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error> { let vault_dir = VaultDiskDirectory::create(&self.path, name, key)?; Ok(Box::new(vault_dir)) } fn open(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error> { let vault_dir = VaultDiskDirectory::at(&self...
random_line_split
disk.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
}) .collect()) } fn vault_meta(&self, name: &str) -> Result<String, Error> { VaultDiskDirectory::meta_at(&self.path, name) } } impl KeyFileManager for DiskKeyFileManager { fn read<T>(&self, filename: Option<String>, reader: T) -> Result<SafeAccount, Error> where T: io::Read { let key_file = json::KeyFi...
{ None }
conditional_block
disk.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn insert(&self, account: SafeAccount) -> Result<SafeAccount, Error> { // build file path let filename = account.filename.as_ref().cloned().unwrap_or_else(|| { let timestamp = time::strftime("%Y-%m-%dT%H-%M-%S", &time::now_utc()).expect("Time-format string is valid."); format!("UTC--{}Z--{}", timestamp, Uu...
{ // Disk store handles updates correctly iff filename is the same self.insert(account) }
identifier_body
disk.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() { // given let mut dir = env::temp_dir(); dir.push("ethstore_should_create_new_account"); let keypair = Random.generate().unwrap(); let password = "hello world"; let directory = RootDiskDirectory::create(dir.clone()).unwrap(); // when let account = SafeAccount::create(&keypair, [0u8; 16], password, ...
should_create_new_account
identifier_name
main.rs
extern crate clap; extern crate colored; extern crate glob; extern crate libc; extern crate regex; //#[macro_use] extern crate itertools; mod replacer; mod operation_mode; mod interactor; mod arguments; mod fs_walker; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use std::fs::{remove_file, rename, F...
} pub fn main() { let args = arguments::parse(); let mode = if args.regex_enabled { operation_mode::OperationMode::new_regex(&args.search_pattern).expect("Invalid regex") } else { operation_mode::OperationMode::new_raw(&args.search_pattern) }; colored::control::set_override(!args...
{ format!("prep_tmp_file_{}", unsafe { getpid() }) }
identifier_body
main.rs
extern crate clap; extern crate colored; extern crate glob; extern crate libc; extern crate regex; //#[macro_use] extern crate itertools; mod replacer; mod operation_mode; mod interactor; mod arguments; mod fs_walker; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use std::fs::{remove_file, rename, F...
() -> TemporaryPrepFile { let filename = Self::generate_filename(); let wf = File::create(&filename).expect("Could not create temporary file"); TemporaryPrepFile { writer: BufWriter::new(wf), filename: filename, } } fn filename(&self) -> &str { re...
new
identifier_name
main.rs
extern crate clap; extern crate colored; extern crate glob; extern crate libc; extern crate regex; //#[macro_use] extern crate itertools; mod replacer; mod operation_mode; mod interactor; mod arguments; mod fs_walker; use std::io::{BufReader, BufWriter}; use std::io::prelude::*; use std::fs::{remove_file, rename, F...
write!(tmp.writer, "{}{}", line, line_end) .expect("Failed to write line to temp file."); curr = next; next = line_iterator.next(); } if did_at_least_one_replacement { let _ = tmp.writer.flush(); ...
random_line_split
render_all_data.rs
use std::collections::BTreeMap; use time::*; use error::Error; use types::{ AllData, CCode, CEnumVariant, CTree, Command, KeyDefs, KmapPath, ModeName, Modifier, Name, SeqType, ToC, }; use output::{KmapBuilder, ModeBuilder}; use util::usize_to_u8; impl AllData { /// Generate and save the c code containin...
/// Used for testing. The message contains a timestamp that would make the /// same output files look different if they're only generated at different /// times. #[cfg(test)] pub fn save_without_message_as( &self, file_name_base: &str, ) -> Result<(), Error> { self.save...
{ self.save_helper(file_name_base, true) }
identifier_body
render_all_data.rs
use std::collections::BTreeMap; use time::*; use error::Error; use types::{ AllData, CCode, CEnumVariant, CTree, Command, KeyDefs, KmapPath, ModeName, Modifier, Name, SeqType, ToC, }; use output::{KmapBuilder, ModeBuilder}; use util::usize_to_u8; impl AllData { /// Generate and save the c code containin...
values: self .get_anagram_mod_numbers()? .iter() .map(|num| num.to_c()) .collect(), c_type: "uint8_t".to_c(), is_extern: true, }); group.push(CTree::StdArray { name: "plain_mod_keys".to_c(), ...
}); group.push(CTree::StdArray { name: "anagram_mod_numbers".to_c(),
random_line_split
render_all_data.rs
use std::collections::BTreeMap; use time::*; use error::Error; use types::{ AllData, CCode, CEnumVariant, CTree, Command, KeyDefs, KmapPath, ModeName, Modifier, Name, SeqType, ToC, }; use output::{KmapBuilder, ModeBuilder}; use util::usize_to_u8; impl AllData { /// Generate and save the c code containin...
(&self, file_name_base: &str) -> Result<(), Error> { self.save_helper(file_name_base, true) } /// Used for testing. The message contains a timestamp that would make the /// same output files look different if they're only generated at different /// times. #[cfg(test)] pub fn save_withou...
save_as
identifier_name
render_all_data.rs
use std::collections::BTreeMap; use time::*; use error::Error; use types::{ AllData, CCode, CEnumVariant, CTree, Command, KeyDefs, KmapPath, ModeName, Modifier, Name, SeqType, ToC, }; use output::{KmapBuilder, ModeBuilder}; use util::usize_to_u8; impl AllData { /// Generate and save the c code containin...
group.push(CTree::LiteralH("#pragma once\n".to_c())); group.push(CTree::IncludeSelf); group.push(CTree::IncludeH { path: "<Arduino.h>".to_c(), }); group.push(CTree::IncludeH { path: "<stdint.h>".to_c(), }); group.push(CTree::IncludeH { path: "\"config_types.h\"".to_...
{ let msg = autogen_message(); group.push(CTree::LiteralC(msg.clone())); group.push(CTree::LiteralH(msg)); }
conditional_block
issue-9396.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let (tx, rx) = channel(); spawn(proc (){ let mut timer = Timer::new().unwrap(); timer.sleep(10); tx.send(()); }); loop { match rx.try_recv() { comm::Data(()) => break, comm::Empty => {} comm::Disconnected => unreachable!() ...
main
identifier_name
issue-9396.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let (tx, rx) = channel(); spawn(proc (){ let mut timer = Timer::new().unwrap(); timer.sleep(10); tx.send(()); }); loop { match rx.try_recv() { comm::Data(()) => break, comm::Empty => {} comm::Disconnected => unreachable!...
// except according to those terms. use std::comm; use std::io::timer::Timer;
random_line_split
issue-9396.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let (tx, rx) = channel(); spawn(proc (){ let mut timer = Timer::new().unwrap(); timer.sleep(10); tx.send(()); }); loop { match rx.try_recv() { comm::Data(()) => break, comm::Empty => {} comm::Disconnected => unreachable!() } ...
identifier_body
metadata.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::fs::Metadata; #[cfg(any(target_os = "macos", target_os = "linux"))] use nix::sys::stat::Mode; #[cfg(target_os = "linux")] use std...
fn eden_dev(&self) -> u64 { // Dummy value 0 } fn eden_file_size(&self) -> u64 { self.file_size() } fn is_setuid_set(&self) -> bool { // This doesn't exist for windows false } } #[cfg(target_os = "linux")] impl MetadataExt for Metadata { fn eden_dev...
fn is_setuid_set(&self) -> bool; } #[cfg(windows)] impl MetadataExt for Metadata {
random_line_split
metadata.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::fs::Metadata; #[cfg(any(target_os = "macos", target_os = "linux"))] use nix::sys::stat::Mode; #[cfg(target_os = "linux")] use std...
fn is_setuid_set(&self) -> bool { // This doesn't exist for windows false } } #[cfg(target_os = "linux")] impl MetadataExt for Metadata { fn eden_dev(&self) -> u64 { self.st_dev() } fn eden_file_size(&self) -> u64 { // Use st_blocks as this represents the actual a...
{ self.file_size() }
identifier_body
metadata.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::fs::Metadata; #[cfg(any(target_os = "macos", target_os = "linux"))] use nix::sys::stat::Mode; #[cfg(target_os = "linux")] use std...
(&self) -> u64 { // Use st_blocks as this represents the actual amount of // disk space allocated by the file, not its apparent // size. self.st_blocks() * 512 } fn is_setuid_set(&self) -> bool { let isuid = Mode::S_ISUID; self.st_mode() & isuid.bits()!= 0 } ...
eden_file_size
identifier_name
prelude.rs
// Copyright (C) 2017 Pietro Albini // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. //! Prelude for Fisher. //! //! This module re-exports useful...
// the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of
random_line_split
move-3.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 x = @Triple{x: 1, y: 2, z: 3}; for _i in range(0u, 10000u) { assert_eq!(test(true, x), 2); } assert_eq!(test(false, x), 5); }
main
identifier_name
move-3.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
return y.y; } pub fn main() { let x = @Triple{x: 1, y: 2, z: 3}; for _i in range(0u, 10000u) { assert_eq!(test(true, x), 2); } assert_eq!(test(false, x), 5); }
fn test(x: bool, foo: @Triple) -> int { let bar = foo; let mut y: @Triple; if x { y = bar; } else { y = @Triple{x: 4, y: 5, z: 6}; }
random_line_split
move-3.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 { y = @Triple{x: 4, y: 5, z: 6}; } return y.y; } pub fn main() { let x = @Triple{x: 1, y: 2, z: 3}; for _i in range(0u, 10000u) { assert_eq!(test(true, x), 2); } assert_eq!(test(false, x), 5); }
{ y = bar; }
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. */ #![deny(warnings)] /// We have a few jobs that maintain some counters for each Mononoke repository. For example, /// the latest blobimport...
else { TransactionResult::Failed }) } }
{ TransactionResult::Succeeded(txn) }
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. */ #![deny(warnings)] /// We have a few jobs that maintain some counters for each Mononoke repository. For example, /// the latest blobimport...
ctx: CoreContext, repoid: RepositoryId, name: &str, ) -> BoxFuture<Option<i64>, Error>; /// Set the current value of the counter. if `prev_value` is not None, then it sets the value /// conditionally. fn set_counter( &self, ctx: CoreContext, repoid: Repos...
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] /// We have a few jobs that maintain some counters for each Mononoke repository. For example, /// the latest blobimport...
}) } }
{ ctx.perf_counters() .increment_counter(PerfCounterType::SqlWrites); let (txn, result) = if let Some(prev_value) = prev_value { SetCounterConditionally::query_with_transaction( txn, &repoid, &name, &value, ...
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] /// We have a few jobs that maintain some counters for each Mononoke repository. For example, /// the latest blobimport...
{ write_connection: Connection, read_connection: Connection, read_master_connection: Connection, } impl SqlConstruct for SqlMutableCounters { const LABEL: &'static str = "mutable_counters"; const CREATION_QUERY: &'static str = include_str!("../schemas/sqlite-mutable-counters.sql"); fn from_s...
SqlMutableCounters
identifier_name
wasm_testsuite.rs
use cranelift_codegen::isa; use cranelift_codegen::print_errors::pretty_verifier_error; use cranelift_codegen::settings::{self, Flags}; use cranelift_codegen::verifier; use cranelift_wasm::{translate_module, DummyEnvironment, ReturnMode}; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::pa...
(path: &Path) -> io::Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::new(); let mut file = File::open(path)?; file.read_to_end(&mut buf)?; Ok(buf) } fn handle_module(path: &Path, flags: &Flags, return_mode: ReturnMode) { let data = match path.extension() { None => { panic!("the fi...
read_file
identifier_name
wasm_testsuite.rs
use cranelift_codegen::isa; use cranelift_codegen::print_errors::pretty_verifier_error; use cranelift_codegen::settings::{self, Flags}; use cranelift_codegen::verifier; use cranelift_wasm::{translate_module, DummyEnvironment, ReturnMode}; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::pa...
fn read_file(path: &Path) -> io::Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::new(); let mut file = File::open(path)?; file.read_to_end(&mut buf)?; Ok(buf) } fn handle_module(path: &Path, flags: &Flags, return_mode: ReturnMode) { let data = match path.extension() { None => { ...
{ let flags = Flags::new(settings::builder()); handle_module( Path::new("../wasmtests/use_fallthrough_return.wat"), &flags, ReturnMode::FallthroughReturn, ); }
identifier_body