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
statistic.rs
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory. // // 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-...
let subject = Subject::local("test"); assert_eq!(Duration::zero(), statistic.average("test", &Link::Local)); statistic.push(subject.clone(), Duration::milliseconds(100)); assert_eq!(Duration::milliseconds(100), statistic.average("test", &Link::Local)); } #[t...
#[test] fn add() { let statistic = Statistic::new();
random_line_split
statistic.rs
// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory. // // 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-...
#[test] fn average() { let statistic = Statistic::new(); let subject = Subject::local("test"); statistic.push(subject.clone(), Duration::milliseconds(100)); statistic.push(subject.clone(), Duration::milliseconds(200)); assert_eq!(Duration::milliseconds(150), ...
{ let statistic = Statistic::new(); let subject = Subject::local("test"); assert_eq!(Duration::zero(), statistic.average("test", &Link::Local)); statistic.push(subject.clone(), Duration::milliseconds(100)); assert_eq!(Duration::milliseconds(100), statistic.av...
identifier_body
select.rs
use std::ptr; use std::os::unix::io::RawFd; use std::cmp; use std::io::{Result, Error}; use std::time::Duration; use std::mem; use std::fmt; use libc; use event::{self, EventSet}; // Returns the highest file descriptor in the given `fd_set`, searching backwards from `prev_max`. fn find_max(set: &libc::fd_set, prev_ma...
(&mut self, fd: RawFd) -> Result<()> { unsafe { libc::FD_CLR(fd, &mut self.rfds); libc::FD_CLR(fd, &mut self.rfds); } // If we removed the highest file descriptor, find the new maximum. if fd == self.maxfd { self.maxfd = cmp::max(find_max(&self.rfds, ...
deregister
identifier_name
select.rs
use std::ptr; use std::os::unix::io::RawFd; use std::cmp; use std::io::{Result, Error}; use std::time::Duration; use std::mem; use std::fmt; use libc; use event::{self, EventSet}; // Returns the highest file descriptor in the given `fd_set`, searching backwards from `prev_max`. fn find_max(set: &libc::fd_set, prev_ma...
else { let mut evset = EventSet::empty(); if is_read { evset.insert(event::READABLE); } if is_write { evset.insert(event::WRITABLE); } let fired = Fired { fd: se...
{ self.curfd += 1; continue; }
conditional_block
select.rs
use std::ptr; use std::os::unix::io::RawFd; use std::cmp; use std::io::{Result, Error}; use std::time::Duration; use std::mem; use std::fmt; use libc; use event::{self, EventSet}; // Returns the highest file descriptor in the given `fd_set`, searching backwards from `prev_max`. fn find_max(set: &libc::fd_set, prev_ma...
let isset = unsafe { libc::FD_ISSET(i, &self.wfds) }; if isset { wfds.push(i); } } f.debug_struct("Iter") .field("maxfd", &self.maxfd) .field("curfd", &self.curfd) .field("rfds", &rfds) .field("wfds", &wfds)...
let mut wfds = Vec::new(); for i in 0..(self.maxfd + 1) {
random_line_split
shadowroot.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> { // Return the result of running the retargeting algorithm with context object // and the original result as input. match self.document_or_shadow_root.element_from_point( x, y, None, ...
ElementFromPoint
identifier_name
shadowroot.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the /// correct tree position. #[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily. pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) { let stylesheets = &mut self.author_st...
{ let stylesheets = &self.author_styles.borrow().stylesheets; stylesheets .get(index) .and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet()) }
identifier_body
shadowroot.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
pub fn stylesheet_count(&self) -> usize { self.author_styles.borrow().stylesheets.len() } pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> { let stylesheets = &self.author_styles.borrow().stylesheets; stylesheets .get(index) .and_th...
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> { //XXX get retargeted focused element None }
random_line_split
shadowroot.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
} }
{ author_styles.flush::<E>(device, quirks_mode, guard); }
conditional_block
channel.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 recv(&mut self) -> Result<T, Failure> { loop { match self.try_recv() { Err(Failure::Empty) => {} data => { return data }, } thread::yield_now(); } } pub fn try_recv(&self) -> Result<T, Failure> { match sel...
{ match self.cnt.fetch_sub(1, Ordering::SeqCst) { DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); } n => { assert!(n >= 0); } } }
identifier_body
channel.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) { self.channels.fetch_add(1, Ordering::SeqCst); } // [@chrino] // Prepares this shared packet for a channel clone, essentially just bumping // a refcount. pub fn clone_port(&self) { self.ports.fetch_add(1, Ordering::SeqCst); } // Decrement the reference count on a c...
clone_chan
identifier_name
channel.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 ...
} } } } } impl<T> Drop for Canal<T> { fn drop(&mut self) { assert_eq!(self.cnt.load(Ordering::SeqCst), DISCONNECTED); assert_eq!(self.channels.load(Ordering::SeqCst), 0); assert_eq!(self.ports.load(Ordering::SeqCst), 0); } } #[cfg(test)] mod test...
None => break,
random_line_split
task.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 ...
(*c_void, Option<~fn(*c_void)>); pub struct Unwinder { unwinding: bool, } impl Task { pub fn new() -> Task { Task { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(ptr::null(), None), logger: StdErrLogger, unwinder: Some(U...
LocalStorage
identifier_name
task.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 ...
let env = transmute(closure.env); let token = rust_try(try_fn, code, env); assert!(token == 0 || token == UNWIND_TOKEN); } extern fn try_fn(code: *c_void, env: *c_void) { unsafe { let closure: Closure = Closure { code:...
unsafe { let closure: Closure = transmute(f); let code = transmute(closure.code);
random_line_split
task.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.destroyed = true; } } impl Drop for Task { fn drop(&self) { assert!(self.destroyed) } } // Just a sanity check to make sure we are catching a Rust-thrown exception static UNWIND_TOKEN: uintptr_t = 839147; impl Unwinder { pub fn try(&mut self, f: &fn()) { ...
{ (*dtor)(ptr) }
conditional_block
htmlobjectelement.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::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
impl Validatable for HTMLObjectElement {} impl VirtualMethods for HTMLObjectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap(...
// https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } }
random_line_split
htmlobjectelement.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::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &atom!("data") => { if let AttributeMutation::Set(_) = mutation { self.process_data_url(); } ...
attribute_mutated
identifier_name
htmlobjectelement.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::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
} } } pub fn is_image_data(uri: &str) -> bool { static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"]; TYPES.iter().any(|&type_| uri.starts_with(type_)) } impl HTMLObjectElementMethods for HTMLObjectElement { // https://html.spec.whatwg.org/multipage...
{ }
conditional_block
htmlobjectelement.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::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLObjectElementB...
} trait ProcessDataURL { fn process_data_url(&self); } impl<'a> ProcessDataURL for &'a HTMLObjectElement { // Makes the local `data` member match the status of the `data` attribute and starts /// prefetching the image. This method must be called after `data` is changed. fn process_data_url(&self) { ...
{ let element = HTMLObjectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap) }
identifier_body
mod.rs
use color::Color; use ray::Ray; use intersection::Intersection; use scene::Scene; /// /// See https://google.github.io/filament//Materials.md.html#materialmodels/litmodel /// /// In Google Filament they refer to /// - The Lit model (standard material model) /// - Subsurface model /// - Cloth model /// /// In PBRT the...
{ Zero, // Can be derived parametrically from the interaction. ~/repos/dotfiles/motd One, // Can be derived from a single sample, however nested rays may be required. Many, // Can only be derived from a Monte-Carlo integration of many samples. } /* pub trait BSDFToRename{ //fn compute_interactions(&...
SamplesRequired
identifier_name
mod.rs
use color::Color; use ray::Ray; use intersection::Intersection; use scene::Scene; /// /// See https://google.github.io/filament//Materials.md.html#materialmodels/litmodel ///
/// In PBRT they refer to /// - a "bidirectional reflectance distribution function (BRDF)" /// - a "bidirectional transmission distribution function (BTDF) /// - a "bidirectional scattering distribution function (BSDF) /// - a "bidirectional sub-surface scattering distribution function BSSRDF" /// /// In Raytracing i...
/// In Google Filament they refer to /// - The Lit model (standard material model) /// - Subsurface model /// - Cloth model ///
random_line_split
macros.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 ...
); ($msg:expr) => ({ static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); ::core::panicking::panic(&_MSG_FILE_LINE) }); ($fmt:expr, $($arg:tt)*) => ({ // The leading _'s are to avoid dead code warnings if this is // used inside a dead funct...
macro_rules! panic { () => ( panic!("explicit panic")
random_line_split
rc4_md5.rs
//! Rc4Md5 cipher definition use crate::crypto::{ digest::{self, Digest, DigestType}, openssl::OpenSSLCrypto, CipherResult, CipherType, CryptoMode, StreamCipher, }; use bytes::{BufMut, BytesMut}; /// Rc4Md5 Cipher pub struct Rc4Md5Cipher { crypto: OpenSSLCrypto, } impl Rc4Md5Cipher { ...
crypto: OpenSSLCrypto::new(CipherType::Rc4, &key, b"", mode), } } } impl StreamCipher for Rc4Md5Cipher { fn update<B: BufMut>(&mut self, data: &[u8], out: &mut B) -> CipherResult<()> { self.crypto.update(data, out) } fn finalize<B: BufMut>(&mut self, out: &mut B) -> CipherR...
Rc4Md5Cipher {
random_line_split
rc4_md5.rs
//! Rc4Md5 cipher definition use crate::crypto::{ digest::{self, Digest, DigestType}, openssl::OpenSSLCrypto, CipherResult, CipherType, CryptoMode, StreamCipher, }; use bytes::{BufMut, BytesMut}; /// Rc4Md5 Cipher pub struct Rc4Md5Cipher { crypto: OpenSSLCrypto, } impl Rc4Md5Cipher { ...
() { let msg = b"abcd1234"; let key = b"key"; let t = CipherType::Rc4Md5; let iv = t.gen_init_vec(); let mut enc = Rc4Md5Cipher::new(key, &iv[..], CryptoMode::Encrypt); let mut encrypted_msg = Vec::new(); enc.update(msg, &mut encrypted_msg) .and_then(...
test_rc4_md5_cipher
identifier_name
class-impl-very-parameterized-trait.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
else { None } } } impl<T> MutableMap<int, T> for cat<T> { fn insert(&mut self, k: int, _: T) -> bool { self.meows += k; true } fn find_mut<'a>(&'a mut self, _k: &int) -> Option<&'a mut T> { fail!() } fn remove(&mut self, k: &int) -> bool { if self.find...
{ Some(&self.name) }
conditional_block
class-impl-very-parameterized-trait.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan"); for _ in range(1u, 5) { nyan.speak(); } assert!(*nyan.find(&1).unwrap() == ~"nyan"); assert_eq!(nyan.find(&10)...
impl<T> cat<T> { fn meow(&mut self) { self.meows += 1;
random_line_split
class-impl-very-parameterized-trait.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self, _k: int, _v: T) -> Option<T> { fail!() } } impl<T> cat<T> { pub fn get<'a>(&'a self, k: &int) -> &'a T { match self.find(k) { Some(v) => { v } None => { fail!("epic fail"); } } } pub fn new(in_x: int, in_y: int, in_name: T) -> cat<T> { cat{meows: ...
swap
identifier_name
class-impl-very-parameterized-trait.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} impl<T> cat<T> { fn meow(&mut self) { self.meows += 1; println!("Meow {}", self.meows); if self.meows % 5 == 0 { self.how_hungry += 1; } } } pub fn main() { let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan"); for _ in range(1u, 5) { nyan.speak(); } ass...
{ cat{meows: in_x, how_hungry: in_y, name: in_name } }
identifier_body
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() -> Option<Box<Terminal<WriterWrapper> + Send>> { let ti: Option<TerminfoTerminal<WriterWrapper>> = Terminal::new(WriterWrapper { wrapped: box std::io::stdout() as Box<Writer + Send>, }); ti.map(|t| box t as Box<Terminal<WriterWrapper> + Send>) } #[cfg(windows)] /// Return a Termi...
stdout
identifier_name
lib.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}); ti.map(|t| box t as Box<Terminal<WriterWrapper> + Send>) } #[cfg(windows)] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send> + Send> { let ti: Option<TerminfoTerminal<WriterWrapper>> = Terminal:...
= Terminal::new(WriterWrapper { wrapped: box std::io::stderr() as Box<Writer + Send>,
random_line_split
drop.rs
struct Present { num: i32, unit: &'static str, } impl Drop for Present { fn
(&mut self) { println!("Drop: {}{}", self.num, self.unit); // ここでdropされる } } fn main() { let present = Present {num: 5000, unit: "兆円"}; println!("貰えないバージョン"); println!("{}{}欲しい!!!", present.num, present.unit); drop(present); // dropされたのでエラーとなる // println!("{}{}貰えなかった", present.num, present.unit); let prese...
drop
identifier_name
drop.rs
struct Present { num: i32, unit: &'static str, } impl Drop for Present { fn drop(&mut self) { println!("Drop: {}{}", self.num, self.unit); // ここでdropされる } } fn main() { let present = Present {num: 5000, unit: "兆円"}; println!("貰えないバージョン"); println!("{}{}欲しい!!!", present.num, present.unit); drop(present); ...
let present2 = Present {num: 5000, unit: "兆円"}; println!("\n貰えるバージョン"); println!("{}{}欲しい!!!", present2.num, present2.unit); drop(&present2); println!("{}{}貰える", present2.num, present2.unit); // ここでpresent2はdropされる }
random_line_split
drop.rs
struct Present { num: i32, unit: &'static str, } impl Drop for Present { fn drop(&mut self)
) { let present = Present {num: 5000, unit: "兆円"}; println!("貰えないバージョン"); println!("{}{}欲しい!!!", present.num, present.unit); drop(present); // dropされたのでエラーとなる // println!("{}{}貰えなかった", present.num, present.unit); let present2 = Present {num: 5000, unit: "兆円"}; println!("\n貰えるバージョン"); println!("{}{}欲しい!!!", pre...
{ println!("Drop: {}{}", self.num, self.unit); // ここでdropされる } } fn main(
identifier_body
proc_macro_impl.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let msg = "proc macro panicked"; let mut err = ecx.struct_span_fatal(span, msg); if let Some(s) = e.as_str() { err.help(&format!("message: {}", s)); } err.emit(); FatalError.raise(); } ...
let server = ::proc_macro_server::Rustc::new(ecx); match self.client.run(&EXEC_STRATEGY, server, input) { Ok(stream) => stream, Err(e) => {
random_line_split
proc_macro_impl.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ pub client: ::proc_macro::bridge::client::Client< fn(::proc_macro::TokenStream) -> ::proc_macro::TokenStream, >, } impl base::ProcMacro for BangProcMacro { fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt, span: Span, input: TokenStream) ...
BangProcMacro
identifier_name
proc_macro_impl.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ let server = ::proc_macro_server::Rustc::new(ecx); match self.client.run(&EXEC_STRATEGY, server, input) { Ok(stream) => stream, Err(e) => { let msg = "proc macro panicked"; let mut err = ecx.struct_span_fatal(span, msg); if let So...
identifier_body
issue-7563.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 ...
} #[deriving(Show)] struct A { a: int } #[deriving(Show)] struct B<'a> { b: int, pa: &'a A } impl IDummy for A { fn do_nothing(&self) { println!("A::do_nothing() is called"); } } impl<'a> B<'a> { fn get_pa(&self) -> &'a IDummy { self.pa as &'a IDummy } } pub fn main() { l...
trait IDummy { fn do_nothing(&self);
random_line_split
issue-7563.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 sa = A { a: 100 }; let sb = B { b: 200, pa: &sa }; println!("sa is {}", sa); println!("sb is {}", sb); }
main
identifier_name
issue-7563.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 sa = A { a: 100 }; let sb = B { b: 200, pa: &sa }; println!("sa is {}", sa); println!("sb is {}", sb); }
{ self.pa as &'a IDummy }
identifier_body
main.rs
extern crate ncurses; mod messages; mod display; mod feature; mod gamestate; use ncurses::*; use std::sync::mpsc::{channel, Sender}; use std::thread; use std::time::Duration; use messages::*; use gamestate::{State,Story}; fn countdown(tx: Sender<MainLoopMsg>) { loop { thread::sleep(Duration::from_milli...
fn main() { // set up game state let mut gamestate = State::new(); init_test_gamestate(&mut gamestate); display::init_ncurses(); // Title sequence stuff display::main_intro(); display::tutorial(); // we want to get full commands now, while updating display, so we need to use halfde...
{ // some test stories let story = Story::new("Gorilla Isn't Mist".to_string(), 525); gamestate.publish(story); let story = Story::new("A Nation Mourns".to_string(), 525); gamestate.publish(story); }
identifier_body
main.rs
extern crate ncurses; mod messages; mod display; mod feature; mod gamestate; use ncurses::*; use std::sync::mpsc::{channel, Sender}; use std::thread; use std::time::Duration; use messages::*; use gamestate::{State,Story}; fn countdown(tx: Sender<MainLoopMsg>) { loop { thread::sleep(Duration::from_milli...
else { // update game state by publishing new story let story = Story::new(gamestate.draft_headline.clone(), 423); gamestate.publish(story); gamestate.draft_headline = String::new(); display::update_screen(&gamestate); } ...
{ unsafe { gamestate.draft_headline.as_mut_vec().push(ch as u8); } }
conditional_block
main.rs
extern crate ncurses; mod messages; mod display; mod feature; mod gamestate; use ncurses::*; use std::sync::mpsc::{channel, Sender}; use std::thread; use std::time::Duration; use messages::*; use gamestate::{State,Story}; fn countdown(tx: Sender<MainLoopMsg>) { loop { thread::sleep(Duration::from_milli...
() { // set up game state let mut gamestate = State::new(); init_test_gamestate(&mut gamestate); display::init_ncurses(); // Title sequence stuff display::main_intro(); display::tutorial(); // we want to get full commands now, while updating display, so we need to use halfdelay+echo ...
main
identifier_name
main.rs
extern crate ncurses; mod messages; mod display; mod feature; mod gamestate; use ncurses::*; use std::sync::mpsc::{channel, Sender}; use std::thread; use std::time::Duration; use messages::*; use gamestate::{State,Story}; fn countdown(tx: Sender<MainLoopMsg>) { loop { thread::sleep(Duration::from_milli...
// Paint the starting screen now display::update_screen(&gamestate); // spawn a thread to handle the game timer: this will refresh screen once a second let (mainloop_tx, mainloop_rx) = channel(); thread::spawn(move|| { countdown(mainloop_tx); }); // Check for keyboard input ...
random_line_split
zero-sized-vec-deque-push.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 ...
// Zero sized type struct Zst; // Test that for all possible sequences of push_front / push_back, // we end up with a deque of the correct size for len in 0..N { let mut tester = VecDeque::with_capacity(len); assert_eq!(tester.len(), 0); assert!(tester.capacity() >= len); ...
use std::collections::VecDeque; use std::iter::Iterator; fn main() { const N: usize = 8;
random_line_split
zero-sized-vec-deque-push.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 ...
() { const N: usize = 8; // Zero sized type struct Zst; // Test that for all possible sequences of push_front / push_back, // we end up with a deque of the correct size for len in 0..N { let mut tester = VecDeque::with_capacity(len); assert_eq!(tester.len(), 0); assert...
main
identifier_name
zero-sized-vec-deque-push.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 ...
} } assert_eq!(tester.len(), len); assert_eq!(tester.iter().count(), len); tester.clear(); } } }
{ const N: usize = 8; // Zero sized type struct Zst; // Test that for all possible sequences of push_front / push_back, // we end up with a deque of the correct size for len in 0..N { let mut tester = VecDeque::with_capacity(len); assert_eq!(tester.len(), 0); assert!(t...
identifier_body
zero-sized-vec-deque-push.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 ...
} assert_eq!(tester.len(), len); assert_eq!(tester.iter().count(), len); tester.clear(); } } }
{ tester.push_back(Zst); }
conditional_block
common.rs
// This file is released into Public Domain. extern crate getopts; use self::getopts::*; use std::env; use gnuplot::*; #[derive(Copy, Clone)] pub struct BetterIterator<'l, T: 'l> { idx: usize, slice: &'l [T] } impl<'l, T: 'l> Iterator for BetterIterator<'l, T> { type Item = &'l T; fn next(&mut self) -> Option<&...
fg.echo_to_file(filename); } pub fn set_term(&self, fg: &mut Figure) { self.term.as_ref().map(|t| { fg.set_terminal(&t[..], ""); }); } }
{ fg.show(); }
conditional_block
common.rs
// This file is released into Public Domain. extern crate getopts; use self::getopts::*; use std::env; use gnuplot::*; #[derive(Copy, Clone)] pub struct BetterIterator<'l, T: 'l> { idx: usize, slice: &'l [T] } impl<'l, T: 'l> Iterator for BetterIterator<'l, T> { type Item = &'l T; fn next(&mut self) -> Option<&...
Some(Common { no_show: matches.opt_present("n"), term: matches.opt_str("t").map(|s| s.to_string()) }) } pub fn show(&self, fg: &mut Figure, filename: &str) { if!self.no_show { fg.show(); } fg.echo_to_file(filename); } pub fn set_term(&self, fg: &mut Figure) { self.term.as_ref().map(|t|...
{ let args: Vec<_> = env::args().collect(); let mut opts = Options::new(); opts.optflag("n", "no-show", "do not run the gnuplot process."); opts.optflag("h", "help", "show this help and exit."); opts.optopt("t", "terminal", "specify what terminal to use for gnuplot.", "TERM"); let matches = match opts.pa...
identifier_body
common.rs
// This file is released into Public Domain. extern crate getopts; use self::getopts::*; use std::env; use gnuplot::*; #[derive(Copy, Clone)] pub struct BetterIterator<'l, T: 'l> { idx: usize, slice: &'l [T] } impl<'l, T: 'l> Iterator for BetterIterator<'l, T> { type Item = &'l T; fn next(&mut self) -> Option<&...
{ fg.show(); } fg.echo_to_file(filename); } pub fn set_term(&self, fg: &mut Figure) { self.term.as_ref().map(|t| { fg.set_terminal(&t[..], ""); }); } }
pub fn show(&self, fg: &mut Figure, filename: &str) { if !self.no_show
random_line_split
common.rs
// This file is released into Public Domain. extern crate getopts; use self::getopts::*; use std::env; use gnuplot::*; #[derive(Copy, Clone)] pub struct BetterIterator<'l, T: 'l> { idx: usize, slice: &'l [T] } impl<'l, T: 'l> Iterator for BetterIterator<'l, T> { type Item = &'l T; fn next(&mut self) -> Option<&...
(self) -> BetterIterator<'l, T> { BetterIterator{ idx: 0, slice: self } } } pub struct Common { pub no_show: bool, pub term: Option<String>, } impl Common { pub fn new() -> Option<Common> { let args: Vec<_> = env::args().collect(); let mut opts = Options::new(); opts.optflag("n", "no-show", "do not ru...
iter2
identifier_name
exercise.rs
use std::fmt::{self, Display, Formatter}; use std::fs::{remove_file, File}; use std::io::Read; use std::path::PathBuf; use std::process::{self, Command, Output}; const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"]; const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE"; const CONTEXT: usize = 2; fn ...
use regex::Regex; use serde::Deserialize;
random_line_split
exercise.rs
use regex::Regex; use serde::Deserialize; use std::fmt::{self, Display, Formatter}; use std::fs::{remove_file, File}; use std::io::Read; use std::path::PathBuf; use std::process::{self, Command, Output}; const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"]; const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+N...
let matched_line_index = source .lines() .enumerate() .filter_map(|(i, line)| if re.is_match(line) { Some(i) } else { None }) .next() .expect("This should not happen at all"); let min_line = ((matched_line_index as i32) - (CONTEXT as i32)).max(0)...
{ return State::Done; }
conditional_block
exercise.rs
use regex::Regex; use serde::Deserialize; use std::fmt::{self, Display, Formatter}; use std::fs::{remove_file, File}; use std::io::Read; use std::path::PathBuf; use std::process::{self, Command, Output}; const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"]; const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+N...
{ pub name: String, pub path: PathBuf, pub mode: Mode, pub hint: String, } #[derive(PartialEq, Debug)] pub enum State { Done, Pending(Vec<ContextLine>), } #[derive(PartialEq, Debug)] pub struct ContextLine { pub line: String, pub number: usize, pub important: bool, } impl Exercis...
Exercise
identifier_name
exercise.rs
use regex::Regex; use serde::Deserialize; use std::fmt::{self, Display, Formatter}; use std::fs::{remove_file, File}; use std::io::Read; use std::path::PathBuf; use std::process::{self, Command, Output}; const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"]; const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+N...
.enumerate() .filter_map(|(i, line)| if re.is_match(line) { Some(i) } else { None }) .next() .expect("This should not happen at all"); let min_line = ((matched_line_index as i32) - (CONTEXT as i32)).max(0) as usize; let max_line = matched_line_index + CONTEXT...
{ let mut source_file = File::open(&self.path).expect("We were unable to open the exercise file!"); let source = { let mut s = String::new(); source_file .read_to_string(&mut s) .expect("We were unable to read the exercise file!"); ...
identifier_body
range_properties.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::engine::PanicEngine; use engine_traits::{Range, RangePropertiesExt, Result}; impl RangePropertiesExt for PanicEngine { fn get_range_approximate_keys(&self, range: Range, large_threshold: u64) -> Result<u64> { panic!() } ...
fn get_range_approximate_size(&self, range: Range, large_threshold: u64) -> Result<u64> { panic!() } fn get_range_approximate_size_cf( &self, cfname: &str, range: Range, large_threshold: u64, ) -> Result<u64> { panic!() } fn get_range_approximate...
}
random_line_split
range_properties.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::engine::PanicEngine; use engine_traits::{Range, RangePropertiesExt, Result}; impl RangePropertiesExt for PanicEngine { fn get_range_approximate_keys(&self, range: Range, large_threshold: u64) -> Result<u64> { panic!() } ...
( &self, range: Range, key_count: usize, ) -> Result<Vec<Vec<u8>>> { panic!() } fn get_range_approximate_split_keys_cf( &self, cfname: &str, range: Range, key_count: usize, ) -> Result<Vec<Vec<u8>>> { panic!() } }
get_range_approximate_split_keys
identifier_name
range_properties.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::engine::PanicEngine; use engine_traits::{Range, RangePropertiesExt, Result}; impl RangePropertiesExt for PanicEngine { fn get_range_approximate_keys(&self, range: Range, large_threshold: u64) -> Result<u64> { panic!() } ...
fn get_range_approximate_size_cf( &self, cfname: &str, range: Range, large_threshold: u64, ) -> Result<u64> { panic!() } fn get_range_approximate_split_keys( &self, range: Range, key_count: usize, ) -> Result<Vec<Vec<u8>>> { ...
{ panic!() }
identifier_body
timers.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::callback::ExceptionHandling::Report; use dom::bindings::cell::DOMRefCell; use dom::bindings::co...
(&self, global: &GlobalScope, callback: TimerCallback, arguments: Vec<HandleValue>, timeout: i32, is_interval: IsInterval, source: Tim...
set_timeout_or_interval
identifier_name
timers.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::callback::ExceptionHandling::Report; use dom::bindings::cell::DOMRefCell; use dom::bindings::co...
scheduled_for: MsDuration, } // This enum is required to work around the fact that trait objects do not support generic methods. // A replacement trait would have a method such as // `invoke<T: DomObject>(self: Box<Self>, this: &T, js_timers: &JsTimers);`. #[derive(JSTraceable, HeapSizeOf)] pub enum OneshotTim...
random_line_split
comp_delib_player.rs
extern crate time; use {Player, MoveResult}; use game_manager::{Game, State}; use gdl::{Move, Score}; /// A bounded compulsive deliberation player. This should only be used for single player games pub struct CompDelibPlayer { depth_limit: u32, best_move: Option<Move>, } impl CompDelibPlayer { /// Returns...
check_time_result!(self, game); } Ok(res) } fn max_score(&mut self, game: &Game, state: &State, moves: &[Move], depth: u32) -> MoveResult<Score> { if depth > self.depth_limit { return Ok(game.goal(state, game.role())); } let cur...
{ max = score; self.best_move = Some(m.clone()); res = m; }
conditional_block
comp_delib_player.rs
extern crate time; use {Player, MoveResult}; use game_manager::{Game, State}; use gdl::{Move, Score}; /// A bounded compulsive deliberation player. This should only be used for single player games pub struct CompDelibPlayer { depth_limit: u32, best_move: Option<Move>, } impl CompDelibPlayer { /// Returns...
(&self) -> String { "CompDelibPlayer".to_string() } fn select_move(&mut self, game: &Game) -> Move { assert!(game.roles().len() == 1, "CompDelibPlayer only works with single player games"); let m = match self.best_move(&game) { Ok(m) => m, Err(m) ...
name
identifier_name
comp_delib_player.rs
extern crate time; use {Player, MoveResult}; use game_manager::{Game, State}; use gdl::{Move, Score}; /// A bounded compulsive deliberation player. This should only be used for single player games pub struct CompDelibPlayer { depth_limit: u32, best_move: Option<Move>, } impl CompDelibPlayer { /// Returns...
if score > max { max = score; self.best_move = Some(m.clone()); res = m; } check_time_result!(self, game); } Ok(res) } fn max_score(&mut self, game: &Game, state: &State, moves: &[Move], depth:...
{ let cur_state = game.current_state(); let mut moves = game.legal_moves(cur_state, game.role()); assert!(moves.len() >= 1, "No legal moves"); if moves.len() == 1 { return Ok(moves.swap_remove(0)); } let mut max = 0; let mut res = moves[0].clone(); ...
identifier_body
comp_delib_player.rs
extern crate time; use {Player, MoveResult}; use game_manager::{Game, State}; use gdl::{Move, Score}; /// A bounded compulsive deliberation player. This should only be used for single player games pub struct CompDelibPlayer { depth_limit: u32, best_move: Option<Move>, } impl CompDelibPlayer { /// Returns...
let moves = game.legal_moves(&cur_state, game.role()); assert!(moves.len() >= 1, "No legal moves"); let mut max = 0; for m in moves { let score = match self.max_score(game, &cur_state, &vec![m], depth + 1) { Ok(score) => score, e @ Err(_) => ...
}
random_line_split
watson.rs
use std::fs::File; use std::io::BufReader; use std::path::PathBuf; use std::thread; use std::time::{Duration, Instant}; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::de::deserialize_local_timestamp; use crate::errors::*; use crate::pro...
s } else { panic!("WatsonState::Idle does not have a specified format") } } }
{ s.push(' '); s.push_str(verb); let delta = Local::now() - *start; s.push(' '); s.push_str(&f(&delta)); }
conditional_block
watson.rs
use std::fs::File; use std::io::BufReader; use std::path::PathBuf; use std::thread; use std::time::{Duration, Instant}; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::de::deserialize_local_timestamp; use crate::errors::*; use crate::pro...
{ Active { project: String, #[serde(deserialize_with = "deserialize_local_timestamp")] start: DateTime<Local>, tags: Vec<String>, }, // This matches an empty JSON object Idle {}, } impl WatsonState { fn format(&self, show_time: bool, verb: &str, f: fn(&chrono::Durat...
WatsonState
identifier_name
watson.rs
use std::fs::File; use std::io::BufReader; use std::path::PathBuf; use std::thread; use std::time::{Duration, Instant}; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::de::deserialize_local_timestamp; use crate::errors::*; use crate::pro...
serde_json::from_reader(file).block_error("watson", "unable to deserialize state")? }; match state { state @ WatsonState::Active {.. } => { self.text.set_state(State::Good); self.text .set_text(state.format(self.show_time, "star...
);
random_line_split
watson.rs
use std::fs::File; use std::io::BufReader; use std::path::PathBuf; use std::thread; use std::time::{Duration, Instant}; use crate::blocks::{Block, ConfigBlock, Update}; use crate::config::SharedConfig; use crate::de::deserialize_duration; use crate::de::deserialize_local_timestamp; use crate::errors::*; use crate::pro...
fn format_delta_after(delta: &chrono::Duration) -> String { let spans = &[ ("week", delta.num_weeks()), ("day", delta.num_days()), ("hour", delta.num_hours()), ("minute", delta.num_minutes()), ("second", delta.num_seconds()), ]; spans .iter() .filter(...
{ let spans = &[ ("week", delta.num_weeks()), ("day", delta.num_days()), ("hour", delta.num_hours()), ("minute", delta.num_minutes()), ]; spans .iter() .filter(|&(_, n)| *n != 0) .map(|&(label, n)| format!("{} {}{} ago", n, label, if n > 1 { "s" } els...
identifier_body
main.rs
extern crate encoding; extern crate minifb; extern crate cpal; extern crate futures; #[macro_use] extern crate clap; extern crate combine; extern crate rustual_boy_core; extern crate rustual_boy_middleware; mod argparse; #[macro_use] mod logging; mod command; mod cpal_driver; mod emulator; mod system_time_sourc...
() { let config = argparse::parse_args(); logln!("Loading ROM file {}", config.rom_path); let rom = Rom::load(&config.rom_path).unwrap(); log!("ROM size: "); if rom.size() >= 1024 * 1024 { logln!("{}MB", rom.size() / 1024 / 1024); } else { logln!("{}KB", rom.size() / 1024); ...
main
identifier_name
main.rs
extern crate encoding; extern crate minifb; extern crate cpal; extern crate futures; #[macro_use] extern crate clap; extern crate combine; extern crate rustual_boy_core; extern crate rustual_boy_middleware; mod argparse; #[macro_use] mod logging; mod command; mod cpal_driver; mod emulator; mod system_time_sourc...
else { logln!("{}KB", rom.size() / 1024); } logln!("Header info:"); logln!(" name: \"{}\"", rom.name().unwrap()); logln!(" maker code: \"{}\"", rom.maker_code().unwrap()); logln!(" game code: \"{}\"", rom.game_code().unwrap()); logln!(" game version: 1.{:#02}", rom.game_version_byte())...
{ logln!("{}MB", rom.size() / 1024 / 1024); }
conditional_block
main.rs
extern crate encoding; extern crate minifb; extern crate cpal; extern crate futures; #[macro_use] extern crate clap; extern crate combine; extern crate rustual_boy_core; extern crate rustual_boy_middleware; mod argparse; #[macro_use] mod logging; mod command; mod cpal_driver; mod emulator; mod system_time_sourc...
logln!("Attempting to load SRAM file: {}", config.sram_path); let sram = match Sram::load(&config.sram_path) { Ok(sram) => { logln!(" SRAM loaded successfully"); sram } Err(err) => { logln!(" Couldn't load SRAM file: {}", err); Sram::new(...
{ let config = argparse::parse_args(); logln!("Loading ROM file {}", config.rom_path); let rom = Rom::load(&config.rom_path).unwrap(); log!("ROM size: "); if rom.size() >= 1024 * 1024 { logln!("{}MB", rom.size() / 1024 / 1024); } else { logln!("{}KB", rom.size() / 1024); }...
identifier_body
main.rs
extern crate encoding; extern crate minifb; extern crate cpal; extern crate futures; #[macro_use] extern crate clap; extern crate combine; extern crate rustual_boy_core; extern crate rustual_boy_middleware; mod argparse; #[macro_use] mod logging; mod command; mod cpal_driver; mod emulator; mod system_time_sourc...
}; let audio_driver = CpalDriver::new(SAMPLE_RATE as _, 100).unwrap(); let audio_buffer_sink = audio_driver.sink(); let time_source = audio_driver.time_source(); let mut emulator = Emulator::new(rom, sram, audio_buffer_sink, time_source); emulator.run(); if emulator.virtual_boy.interconn...
logln!(" Couldn't load SRAM file: {}", err); Sram::new() }
random_line_split
transfer_encoding.rs
use header::{Header, HeaderFormat}; use std::fmt; use header::Encoding; use header::parsing::{from_comma_delimited, fmt_comma_delimited}; /// The `Transfer-Encoding` header. /// /// This header describes the encoding of the message body. It can be /// comma-separated, including multiple encodings. /// /// ```notrust /...
(raw: &[Vec<u8>]) -> Option<TransferEncoding> { from_comma_delimited(raw).map(TransferEncoding) } } impl HeaderFormat for TransferEncoding { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt_comma_delimited(fmt, &self[]) } } bench_header!(normal, TransferEncoding, { vec![...
parse_header
identifier_name
transfer_encoding.rs
use header::{Header, HeaderFormat}; use std::fmt; use header::Encoding; use header::parsing::{from_comma_delimited, fmt_comma_delimited}; /// The `Transfer-Encoding` header. /// /// This header describes the encoding of the message body. It can be /// comma-separated, including multiple encodings. /// /// ```notrust /...
fn parse_header(raw: &[Vec<u8>]) -> Option<TransferEncoding> { from_comma_delimited(raw).map(TransferEncoding) } } impl HeaderFormat for TransferEncoding { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt_comma_delimited(fmt, &self[]) } } bench_header!(normal, Tran...
{ "Transfer-Encoding" }
identifier_body
transfer_encoding.rs
use header::{Header, HeaderFormat}; use std::fmt; use header::Encoding; use header::parsing::{from_comma_delimited, fmt_comma_delimited}; /// The `Transfer-Encoding` header. /// /// This header describes the encoding of the message body. It can be /// comma-separated, including multiple encodings. /// /// ```notrust /...
from_comma_delimited(raw).map(TransferEncoding) } } impl HeaderFormat for TransferEncoding { fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt_comma_delimited(fmt, &self[]) } } bench_header!(normal, TransferEncoding, { vec![b"chunked, gzip".to_vec()] }); bench_header!(ext...
fn parse_header(raw: &[Vec<u8>]) -> Option<TransferEncoding> {
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. */
//! reference count. //! //! Aside from supporting `Vec<u8>` as the underlying storage, [`Bytes`] also //! supports [`memmap::Mmap`]. Libraries can implement [`BytesOwner`] for other //! types to further extend storage support. mod bytes; mod impls; mod owners; mod serde; mod text; #[cfg(test)] mod tests; pub use te...
//! # minibytes //! //! This create provides the [`Bytes`] type. It is similar to `&[u8]`: cloning //! or slicing are zero-copy. Unlike `&[u8]`, `Bytes` does not have lifetime. //! This is done by maintaining the life cycle of the underlying storage using
random_line_split
darcs.rs
use crate::util::process; use anyhow::{anyhow, Result}; use std::{ffi::OsStr, path::Path}; pub fn initialize<P>(path: P) -> Result<()> where P: AsRef<Path>, { process::inherit("darcs") .arg("initialize") .arg(path.as_ref().as_os_str()) .status() .map_err(Into::into) .and_then...
<P, U, I, S>(url: U, path: P, args: I) -> Result<()> where P: AsRef<Path>, U: AsRef<str>, I: IntoIterator<Item = S>, S: AsRef<OsStr>, { let path = format!("{}", path.as_ref().display()); process::inherit("darcs") .arg("clone") .args(args) .args(&[url.as_ref(), &path]) ...
clone
identifier_name
darcs.rs
use crate::util::process; use anyhow::{anyhow, Result}; use std::{ffi::OsStr, path::Path}; pub fn initialize<P>(path: P) -> Result<()> where P: AsRef<Path>, { process::inherit("darcs") .arg("initialize") .arg(path.as_ref().as_os_str()) .status() .map_err(Into::into) .and_then...
.arg("clone") .args(args) .args(&[url.as_ref(), &path]) .status() .map_err(Into::into) .and_then(|st| match st.code() { Some(0) => Ok(()), st => Err(anyhow!( "command 'darcs' is exited with return code {:?}.", st ...
S: AsRef<OsStr>, { let path = format!("{}", path.as_ref().display()); process::inherit("darcs")
random_line_split
darcs.rs
use crate::util::process; use anyhow::{anyhow, Result}; use std::{ffi::OsStr, path::Path}; pub fn initialize<P>(path: P) -> Result<()> where P: AsRef<Path>,
pub fn clone<P, U, I, S>(url: U, path: P, args: I) -> Result<()> where P: AsRef<Path>, U: AsRef<str>, I: IntoIterator<Item = S>, S: AsRef<OsStr>, { let path = format!("{}", path.as_ref().display()); process::inherit("darcs") .arg("clone") .args(args) .args(&[url.as_ref(), ...
{ process::inherit("darcs") .arg("initialize") .arg(path.as_ref().as_os_str()) .status() .map_err(Into::into) .and_then(|st| match st.code() { Some(0) => Ok(()), st => Err(anyhow!( "command 'darcs' is exited with return code {:?}.", ...
identifier_body
cargo_compile.rs
//! //! Cargo compile currently does the following steps: //! //! All configurations are already injected as environment variables via the //! main cargo command //! //! 1. Read the manifest //! 2. Shell out to `cargo-resolve` with a list of dependencies and sources as //! stdin //! //! a. Shell out to `--do upda...
}).map(|p| SourceId::for_path(&p)).collect() } fn scrape_build_config(config: &Config, configs: &HashMap<String, config::ConfigValue>) -> CargoResult<ops::BuildConfig> { let target = match configs.get("target") { None => return Ok(Default::default()), ...
{ debug!("loaded config; configs={:?}", configs); let config_paths = match configs.get("paths") { Some(cfg) => cfg, None => return Ok(Vec::new()) }; let paths = try!(config_paths.list().chain_error(|| { internal("invalid configuration for the key `paths`") })); paths.it...
identifier_body
cargo_compile.rs
//! //! Cargo compile currently does the following steps: //! //! All configurations are already injected as environment variables via the //! main cargo command //! //! 1. Read the manifest //! 2. Shell out to `cargo-resolve` with a list of dependencies and sources as //! stdin //! //! a. Shell out to `--do upda...
for (k, v) in target.iter() { match k.as_slice() { "ar" | "linker" => { let v = try!(v.string().chain_error(|| { internal(format!("invalid configuration for key `{}`", k)) })).0.to_string(); if k.as_slice() == "linker" { ...
linker: None, overrides: HashMap::new(), };
random_line_split
cargo_compile.rs
//! //! Cargo compile currently does the following steps: //! //! All configurations are already injected as environment variables via the //! main cargo command //! //! 1. Read the manifest //! 2. Shell out to `cargo-resolve` with a list of dependencies and sources as //! stdin //! //! a. Shell out to `--do upda...
(configs: &HashMap<String, config::ConfigValue>, cur_path: Path) -> CargoResult<Vec<SourceId>> { debug!("loaded config; configs={:?}", configs); let config_paths = match configs.get("paths") { Some(cfg) => cfg, None => return Ok(Vec::new()) }; let paths = try!(...
source_ids_from_config
identifier_name
nullable.rs
mod nullables; use crate::grammar::ElemTypes; use super::Pass; pub struct
; pub use nullables::{GrammarNullableInfo, NullableError}; impl<E> Pass<E> for Nullable where E: ElemTypes, { type Value = nullables::GrammarNullableInfo<E>; type Error = nullables::NullableError; fn run_pass<'a>(pass_map: &super::PassMap<'a, E>) -> Result<Self::Value, Self::Error> { nullables::calculate...
Nullable
identifier_name
nullable.rs
mod nullables; use crate::grammar::ElemTypes; use super::Pass; pub struct Nullable; pub use nullables::{GrammarNullableInfo, NullableError}; impl<E> Pass<E> for Nullable where E: ElemTypes, { type Value = nullables::GrammarNullableInfo<E>; type Error = nullables::NullableError; fn run_pass<'a>(pass_map: &...
#[test] fn test_simple_nullable_grammar() { let g = examples::make_simple_nullable(); let pass_map = PassMap::new(&g); let nullables = pass_map.get_pass::<Nullable>().unwrap(); assert!(nullables.is_nullable(&NonTerminal::new("start"))); assert!(nullables.is_nullable(&NonTerminal::new("a"))); ...
{ let g = wrap_grammar_with_start(examples::make_simple()).unwrap(); let pass_map = PassMap::new(&g); let nullables = pass_map.get_pass::<Nullable>().unwrap(); assert!(nullables.get_nullable_set().is_empty()); }
identifier_body
nullable.rs
mod nullables; use crate::grammar::ElemTypes; use super::Pass; pub struct Nullable; pub use nullables::{GrammarNullableInfo, NullableError};
E: ElemTypes, { type Value = nullables::GrammarNullableInfo<E>; type Error = nullables::NullableError; fn run_pass<'a>(pass_map: &super::PassMap<'a, E>) -> Result<Self::Value, Self::Error> { nullables::calculate_nullables(pass_map.grammar()) } } #[cfg(test)] mod test { use super::*; use crate::gramm...
impl<E> Pass<E> for Nullable where
random_line_split
simple.rs
extern crate rand; use self::rand::Rng; use core::world::dungeon::map::{self, tile, Tile}; use super::{AI, RANDOM_TRIES}; use core::creature::{Actions, Creature, Actor, Stats}; /// /// SimpleAI is literally just an AI that walks around randomly /// /// NOTE: There is really no intention to keep this AI around... Ma...
(&self) -> Box<dyn AI> { Box::new((*self).clone()) } }
box_clone
identifier_name
simple.rs
extern crate rand; use self::rand::Rng; use core::world::dungeon::map::{self, tile, Tile}; use super::{AI, RANDOM_TRIES}; use core::creature::{Actions, Creature, Actor, Stats}; /// /// SimpleAI is literally just an AI that walks around randomly /// /// NOTE: There is really no intention to keep this AI around... Ma...
// Match dice for movement match dice { 1 => x += 1, 2 => x -= 1, 3 => y += 1, 4 => y -= 1, _ => unreachable!("SimpleAI - Unreachable dice state reached in movement") } // Since the only thing this thing can do is move, there is no need to match the dice...
y += 1; }
random_line_split
test_stateless_writer.rs
use std::default::Default; use rtps::*; use rtps::common_types::*; use factories::Create; #[test] fn test_stateless_writer_heartbeat_increments_count() { let mut writer : StatelessWriter = Create::create(); writer.new_change( ChangeKind::ALIVE, InstanceHandle::new(), ArcBuffer::from_vec(vec!...
*count = 1; } assert_eq!(heartbeat2, common_heartbeat); }
} assert_eq!(heartbeat, common_heartbeat); let heartbeat2 = writer.heartbeat(reader_entity_id); if let SubmessageVariant::Heartbeat{ref mut count, ..} = common_heartbeat {
random_line_split
test_stateless_writer.rs
use std::default::Default; use rtps::*; use rtps::common_types::*; use factories::Create; #[test] fn test_stateless_writer_heartbeat_increments_count()
}; let heartbeat = writer.heartbeat(reader_entity_id); if let SubmessageVariant::Heartbeat{ref mut count,..} = common_heartbeat { *count = 0; } assert_eq!(heartbeat, common_heartbeat); let heartbeat2 = writer.heartbeat(reader_entity_id); if let SubmessageVariant::Heartbeat{ref mut ...
{ let mut writer : StatelessWriter = Create::create(); writer.new_change( ChangeKind::ALIVE, InstanceHandle::new(), ArcBuffer::from_vec(vec![]) ); writer.new_change( ChangeKind::ALIVE, InstanceHandle::new(), ArcBuffer::from_vec(vec![]) ); let reader_entity_id : ...
identifier_body
test_stateless_writer.rs
use std::default::Default; use rtps::*; use rtps::common_types::*; use factories::Create; #[test] fn test_stateless_writer_heartbeat_increments_count() { let mut writer : StatelessWriter = Create::create(); writer.new_change( ChangeKind::ALIVE, InstanceHandle::new(), ArcBuffer::from_vec(vec!...
assert_eq!(heartbeat2, common_heartbeat); }
{ *count = 1; }
conditional_block
test_stateless_writer.rs
use std::default::Default; use rtps::*; use rtps::common_types::*; use factories::Create; #[test] fn
() { let mut writer : StatelessWriter = Create::create(); writer.new_change( ChangeKind::ALIVE, InstanceHandle::new(), ArcBuffer::from_vec(vec![]) ); writer.new_change( ChangeKind::ALIVE, InstanceHandle::new(), ArcBuffer::from_vec(vec![]) ); let reader_entity_id...
test_stateless_writer_heartbeat_increments_count
identifier_name
allocator.rs
use core::mem::transmute; use core::ptr::{set_memory, copy_memory, offset}; use core::i32::ctlz32; use core::fail::out_of_memory; use kernel::ptr::mut_offset; #[repr(u8)] enum Node { UNUSED = 0, USED = 1, SPLIT = 2, FULL = 3 } pub trait Allocator { fn alloc(&mut self, size: uint) -> (*mut u8, uin...
_ => break } } return ( self.offset(index, level), 1 << lg2_size ); } (UNUSED, false) => { // This large no...
{ parent = (parent + 1) / 2 - 1; self.tree.set(parent, FULL); }
conditional_block
allocator.rs
use core::mem::transmute; use core::ptr::{set_memory, copy_memory, offset}; use core::i32::ctlz32; use core::fail::out_of_memory; use kernel::ptr::mut_offset; #[repr(u8)] enum Node { UNUSED = 0, USED = 1, SPLIT = 2, FULL = 3 } pub trait Allocator { fn alloc(&mut self, size: uint) -> (*mut u8, uin...
} } } } impl Allocator for Alloc { fn alloc(&mut self, size: uint) -> (*mut u8, uint) { let (offset, size) = self.parent.alloc(size); unsafe { return ( mut_offset(self.base, (offset << self.el_size) as int), size << self.el_size ...
random_line_split
allocator.rs
use core::mem::transmute; use core::ptr::{set_memory, copy_memory, offset}; use core::i32::ctlz32; use core::fail::out_of_memory; use kernel::ptr::mut_offset; #[repr(u8)] enum Node { UNUSED = 0, USED = 1, SPLIT = 2, FULL = 3 } pub trait Allocator { fn alloc(&mut self, size: uint) -> (*mut u8, uin...
(&self, i: uint) -> Node { let w = i / 16; let b = (i % 16) * 2; unsafe { transmute(((*self.storage)[w] as uint >> b) as u8 & 3) } } #[inline] fn set(&self, i: uint, x: Node) { let w = i / 16; let b = (i % 16) * 2; unsafe { (*self.storage)[w] = (((*self.stora...
get
identifier_name
thread_local.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn pthread_setspecific(key: pthread_key_t, value: *mut u8) -> c_int; }
fn pthread_key_create(key: *mut pthread_key_t, dtor: Option<unsafe extern fn(*mut u8)>) -> c_int; fn pthread_key_delete(key: pthread_key_t) -> c_int; fn pthread_getspecific(key: pthread_key_t) -> *mut u8;
random_line_split
thread_local.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(key: Key) -> *mut u8 { pthread_getspecific(key) } #[inline] pub unsafe fn destroy(key: Key) { let r = pthread_key_delete(key); debug_assert_eq!(r, 0); } #[cfg(any(target_os = "macos", target_os = "ios"))] type pthread_key_t = ::libc::c_ulong; #[cfg(any(target_os = "freebsd", target_o...
get
identifier_name
thread_local.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[inline] pub unsafe fn set(key: Key, value: *mut u8) { let r = pthread_setspecific(key, value); debug_assert_eq!(r, 0); } #[inline] pub unsafe fn get(key: Key) -> *mut u8 { pthread_getspecific(key) } #[inline] pub unsafe fn destroy(key: Key) { let r = pthread_key_delete(key); debug_assert_eq!(r...
{ let mut key = 0; assert_eq!(pthread_key_create(&mut key, dtor), 0); return key; }
identifier_body
point.rs
use super::{Vector3D, AsVector, Direction3D}; #[derive(PartialEq, PartialOrd, Clone, Debug)] pub struct Point3D { pub x: f32, pub y: f32, pub z: f32 } static POINT3D_ORIGIN: Point3D = Point3D { x: 0.0, y: 0.0, z: 0.0 }; impl Point3D { pub fn from_xyz(x: f32, y: f32, z: f32) -> Point3D {...
}
}
random_line_split
point.rs
use super::{Vector3D, AsVector, Direction3D}; #[derive(PartialEq, PartialOrd, Clone, Debug)] pub struct Point3D { pub x: f32, pub y: f32, pub z: f32 } static POINT3D_ORIGIN: Point3D = Point3D { x: 0.0, y: 0.0, z: 0.0 }; impl Point3D { pub fn from_xyz(x: f32, y: f32, z: f32) -> Point3D {...
}
{ Point3D::from_xyz( 0.5 * (point1.x + point2.z), 0.5 * (point1.y + point2.y), 0.5 * (point1.z + point2.z)) }
identifier_body
point.rs
use super::{Vector3D, AsVector, Direction3D}; #[derive(PartialEq, PartialOrd, Clone, Debug)] pub struct
{ pub x: f32, pub y: f32, pub z: f32 } static POINT3D_ORIGIN: Point3D = Point3D { x: 0.0, y: 0.0, z: 0.0 }; impl Point3D { pub fn from_xyz(x: f32, y: f32, z: f32) -> Point3D { Point3D { x: x, y: y, z: z } } pub fn from_v...
Point3D
identifier_name