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
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::sync::Arc; use style::gecko_bindings::bindings::Gecko_LoadStyleSheet; use style::gecko_bindings::structs:...
(loader: *mut Loader, parent: *mut ServoStyleSheet) -> Self { StylesheetLoader(loader, parent) } } impl StyleStylesheetLoader for StylesheetLoader { fn request_stylesheet( &self, media: MediaList, make_import: &mut FnMut(MediaList) -> ImportRule, make_arc: &mut FnMut(Imp...
new
identifier_name
pipe.rs
//! //! Desync pipes provide a way to generate and process streams via a `Desync` object //! //! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping //! a stream into a `Desync` object is equivalent to spawning it with an executor, except //! without the need to dedicate a thread t...
}; // If anything needs notifying, do so outside of the lock notify.map(|notify| notify.wake()); result } }
{ let (result, notify) = { // Fetch the state from the core (locking the state) let mut core = self.core.lock().unwrap(); if let Some(item) = core.pending.pop_front() { // Value waiting at the start of the stream let notify_backpressure = core...
identifier_body
pipe.rs
//! //! Desync pipes provide a way to generate and process streams via a `Desync` object //! //! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping //! a stream into a `Desync` object is equivalent to spawning it with an executor, except //! without the need to dedicate a thread t...
if let Some(stream_core) = stream_core { // Defer processing if the stream core is full let is_closed = { // Fetch the core let mut stream_core = stream_core.lock().unwrap(); // If the pending queue is full, then st...
let mut context = context; let input_stream = Arc::clone(&input_stream); let process = Arc::clone(&process); async move {
random_line_split
pipe.rs
//! //! Desync pipes provide a way to generate and process streams via a `Desync` object //! //! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping //! a stream into a `Desync` object is equivalent to spawning it with an executor, except //! without the need to dedicate a thread t...
}; // If anything needs notifying, do so outside of the lock notify.map(|notify| notify.wake()); result } }
{ // Stream not ready let notify_backpressure = core.backpressure_release_notify.take(); core.notify = Some(context.waker().clone()); (Poll::Pending, notify_backpressure) }
conditional_block
pipe.rs
//! //! Desync pipes provide a way to generate and process streams via a `Desync` object //! //! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping //! a stream into a `Desync` object is equivalent to spawning it with an executor, except //! without the need to dedicate a thread t...
(&mut self) { let mut core = self.core.lock().unwrap(); // Flush the pending queue core.pending = VecDeque::new(); // Mark the core as closed to stop it from reading from the stream core.closed = true; // Wake the stream to finish closing it core.notify_stream_...
drop
identifier_name
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; // check that each char in the slice is either: // 1. %x21, or // 2. in the range %x23 to %x7E, or // 3. in the range %x80 to %xFF fn check_slice_validity(slice: &str) -> bool { slice.bytes().all(|c| c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >...
!self.weak_eq(other) } } impl Display for EntityTag { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.weak { write!(f, "W/\"{}\"", self.tag) } else { write!(f, "\"{}\"", self.tag) } } } impl FromStr for EntityTag { type Err = ::Erro...
/// The inverse of `EntityTag.weak_eq()`. pub fn weak_ne(&self, other: &EntityTag) -> bool {
random_line_split
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; // check that each char in the slice is either: // 1. %x21, or // 2. in the range %x23 to %x7E, or // 3. in the range %x80 to %xFF fn check_slice_validity(slice: &str) -> bool { slice.bytes().all(|c| c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >...
Err(::Error::Header) } } #[cfg(test)] mod tests { use super::EntityTag; #[test] fn test_etag_parse_success() { // Expected success assert_eq!("\"foobar\"".parse::<EntityTag>().unwrap(), EntityTag::strong("foobar".to_owned())); assert_eq!("\"\"".parse::<Enti...
{ return Ok(EntityTag { weak: true, tag: slice[3..length-1].to_owned() }); }
conditional_block
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; // check that each char in the slice is either: // 1. %x21, or // 2. in the range %x23 to %x7E, or // 3. in the range %x80 to %xFF fn check_slice_validity(slice: &str) -> bool { slice.bytes().all(|c| c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >...
(s: &str) -> ::Result<EntityTag> { let length: usize = s.len(); let slice = &s[..]; // Early exits if it doesn't terminate in a DQUOTE. if!slice.ends_with('"') { return Err(::Error::Header); } // The etag is weak if its first char is not a DQUOTE. if s...
from_str
identifier_name
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; // check that each char in the slice is either: // 1. %x21, or // 2. in the range %x23 to %x7E, or // 3. in the range %x80 to %xFF fn check_slice_validity(slice: &str) -> bool { slice.bytes().all(|c| c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >...
#[test] fn test_etag_parse_failures() { // Expected failures assert!("no-dquotes".parse::<EntityTag>().is_err()); assert!("w/\"the-first-w-is-case-sensitive\"".parse::<EntityTag>().is_err()); assert!("".parse::<EntityTag>().is_err()); assert!("\"unmatched-dquotes1".pars...
{ // Expected success assert_eq!("\"foobar\"".parse::<EntityTag>().unwrap(), EntityTag::strong("foobar".to_owned())); assert_eq!("\"\"".parse::<EntityTag>().unwrap(), EntityTag::strong("".to_owned())); assert_eq!("W/\"weaktag\"".parse::<EntityTag>().unwrap(), ...
identifier_body
issue-2817-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 ...
{ for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but false }; for not_bool |_i| { //~^ ERROR A `for` loop iterator should expect a closure that returns `bool` ~"hi" }; for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but ...
identifier_body
issue-2817-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 ...
(f: &fn(int) -> ~str) -> bool {} fn main() { for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but false }; for not_bool |_i| { //~^ ERROR A `for` loop iterator should expect a closure that returns `bool` ~"hi" }; for uint::range(0, 100000) |_i| { //~ E...
not_bool
identifier_name
issue-2817-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 ...
}; }
random_line_split
parsing.rs
//! Utility functions for Header implementations. use language_tags::LanguageTag; use std::str; use std::str::FromStr; use std::fmt::{self, Display}; use url::percent_encoding; use header::Raw; use header::shared::Charset; /// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(...
let extended_value = ExtendedValue { charset: Charset::Iso_8859_1, language_tag: Some("en".parse().expect("Could not parse language tag")), value: vec![163, b' ', b'r', b'a', b't', b'e', b's'], }; assert_eq!("ISO-8859-1'en'%A3%20rates", format!("{}", extended_...
random_line_split
parsing.rs
//! Utility functions for Header implementations. use language_tags::LanguageTag; use std::str; use std::str::FromStr; use std::fmt::{self, Display}; use url::percent_encoding; use header::Raw; use header::shared::Charset; /// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(...
} #[cfg(test)] mod tests { use header::shared::Charset; use super::{ExtendedValue, parse_extended_value}; #[test] fn test_parse_extended_value_with_encoding_and_language_tag() { let expected_language_tag = langtag!(en); // RFC 5987, Section 3.2.2 // Extended notation, using th...
{ let encoded_value = percent_encoding::percent_encode(&self.value[..], HTTP_VALUE); if let Some(ref lang) = self.language_tag { write!(f, "{}'{}'{}", self.charset, lang, encoded_value) } else { write!(f, "{}''{}", self.charset, encoded_value) } }
identifier_body
parsing.rs
//! Utility functions for Header implementations. use language_tags::LanguageTag; use std::str; use std::str::FromStr; use std::fmt::{self, Display}; use url::percent_encoding; use header::Raw; use header::shared::Charset; /// Reads a single raw string when parsing a header. pub fn from_one_raw_str<T: str::FromStr>(...
(&self, f: &mut fmt::Formatter) -> fmt::Result { let encoded_value = percent_encoding::percent_encode(&self.value[..], HTTP_VALUE); if let Some(ref lang) = self.language_tag { write!(f, "{}'{}'{}", self.charset, lang, encoded_value) } else { write!(f, "{}''{}"...
fmt
identifier_name
customevent.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::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
fn InitCustomEvent(self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, detail: JSVal) { let event: JSRef<Event> = EventCast::from_ref(self); if event.disp...
{ self.detail.get() }
identifier_body
customevent.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::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
(self, _cx: *mut JSContext) -> JSVal { self.detail.get() } fn InitCustomEvent(self, _cx: *mut JSContext, type_: DOMString, can_bubble: bool, cancelable: bool, detail: JSVal) { let ...
Detail
identifier_name
customevent.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::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
pub struct CustomEvent { event: Event, detail: MutHeap<JSVal>, } impl CustomEventDerived for Event { fn is_customevent(&self) -> bool { *self.type_id() == EventTypeId::CustomEvent } } impl CustomEvent { fn new_inherited(type_id: EventTypeId) -> CustomEvent { CustomEvent { ...
#[dom_struct]
random_line_split
customevent.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::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding...
self.detail.set(detail); event.InitEvent(type_, can_bubble, cancelable); } }
{ return; }
conditional_block
chacha20.rs
use std::slice; use super::{StreamEncrypt, StreamDecrypt}; use byteorder::{ByteOrder, LittleEndian}; const ROUNDS: usize = 20; const STATE_WORDS: usize = 16; const STATE_BYTES: usize = STATE_WORDS * 4; #[derive(Copy, Clone)] struct State([u32; STATE_WORDS]); macro_rules! quarter_round { ($a:expr, $b:expr, $c:e...
fn update(&mut self, output: &mut [u32]) { let mut state = self.0; for _ in 0..ROUNDS / 2 { double_round!(state); } for i in 0..STATE_WORDS { output[i] = self.0[i].wrapping_add(state[i]); } self.0[12] += 1; } } pub struct ChaCha20 { ...
{ let mut state = [0u32; STATE_WORDS]; state[0] = 0x61707865; state[1] = 0x3320646e; state[2] = 0x79622d32; state[3] = 0x6b206574; for (state, chunk) in state[4..12].iter_mut().zip(key.chunks(4)) { *state = LittleEndian::read_u32(chunk); } s...
identifier_body
chacha20.rs
use std::slice; use super::{StreamEncrypt, StreamDecrypt}; use byteorder::{ByteOrder, LittleEndian}; const ROUNDS: usize = 20; const STATE_WORDS: usize = 16; const STATE_BYTES: usize = STATE_WORDS * 4; #[derive(Copy, Clone)] struct State([u32; STATE_WORDS]); macro_rules! quarter_round { ($a:expr, $b:expr, $c:e...
(&mut self, input: &[u8], output: &mut [u8]) { if self.index == STATE_BYTES { self.update() } let buffer = unsafe { slice::from_raw_parts(self.buffer.as_ptr() as *const u8, STATE_BYTES) }; for i in self.index..input.len() { output[i] = input[...
crypt
identifier_name
chacha20.rs
use std::slice; use super::{StreamEncrypt, StreamDecrypt}; use byteorder::{ByteOrder, LittleEndian}; const ROUNDS: usize = 20; const STATE_WORDS: usize = 16; const STATE_BYTES: usize = STATE_WORDS * 4; #[derive(Copy, Clone)] struct State([u32; STATE_WORDS]); macro_rules! quarter_round { ($a:expr, $b:expr, $c:e...
let buffer = unsafe { slice::from_raw_parts(self.buffer.as_ptr() as *const u8, STATE_BYTES) }; for i in self.index..input.len() { output[i] = input[i] ^ buffer[i]; } self.index = input.len(); } } impl StreamEncrypt for ChaCha20 { fn encrypt_st...
{ self.update() }
conditional_block
chacha20.rs
use std::slice; use super::{StreamEncrypt, StreamDecrypt}; use byteorder::{ByteOrder, LittleEndian}; const ROUNDS: usize = 20; const STATE_WORDS: usize = 16; const STATE_BYTES: usize = STATE_WORDS * 4; #[derive(Copy, Clone)] struct State([u32; STATE_WORDS]); macro_rules! quarter_round { ($a:expr, $b:expr, $c:e...
state: State::expand(key.as_ref(), nonce.as_ref(), position), buffer: [0; STATE_WORDS], index: STATE_BYTES, } } pub fn new<Key, Nonce>(key: Key, nonce: Nonce) -> Self where Key: AsRef<[u8]>, Nonce: AsRef<[u8]> { Self::init(key.as_ref...
pub fn init(key: &[u8], nonce: &[u8], position: u32) -> Self { ChaCha20 {
random_line_split
directory.rs
} /// A Digest for a directory, optionally with its content stored as a DigestTrie. /// /// If a DirectoryDigest has a DigestTrie reference, then its Digest _might not_ be persisted to /// the Store. If the DirectoryDigest does not hold a DigestTrie, then that Digest _must_ have been /// persisted to the Store (either...
/// can directly allocate the collections that they need. pub fn files_and_directories(&self) -> (Vec<PathBuf>, Vec<PathBuf>) { let mut files = Vec::new(); let mut directories = Vec::new(); self.walk(&mut |path, entry| { match entry { Entry::File(_) => files.push(path.to_owned()), ...
/// Return a pair of Vecs of the file paths and directory paths in this DigestTrie, each in /// sorted order. /// /// TODO: This should probably be implemented directly by consumers via `walk`, since they
random_line_split
directory.rs
/// A Digest for a directory, optionally with its content stored as a DigestTrie. /// /// If a DirectoryDigest has a DigestTrie reference, then its Digest _might not_ be persisted to /// the Store. If the DirectoryDigest does not hold a DigestTrie, then that Digest _must_ have been /// persisted to the Store (either ...
/// Creates a DirectoryDigest which asserts that the given Digest represents a Directory structure /// which is persisted in a Store. /// /// Use of this method should be rare: code should prefer to pass around a `DirectoryDigest` rather /// than to create one from a `Digest` (as the latter requires loading...
{ if cfg!(debug_assertions) { assert!(digest == tree.compute_root_digest()); } Self { digest, tree: Some(tree), } }
identifier_body
directory.rs
/// A Digest for a directory, optionally with its content stored as a DigestTrie. /// /// If a DirectoryDigest has a DigestTrie reference, then its Digest _might not_ be persisted to /// the Store. If the DirectoryDigest does not hold a DigestTrie, then that Digest _must_ have been /// persisted to the Store (either ...
(&self) -> &Path { match self { TypedPath::File { path,.. } => path, TypedPath::Dir(d) => d, } } } impl<'a> From<&'a PathStat> for TypedPath<'a> { fn from(p: &'a PathStat) -> Self { match p { PathStat::File { path, stat } => TypedPath::File { path, is_executable: stat....
deref
identifier_name
stack.rs
//! Algorithm 1.2: Pushdown stack. struct Node<T> { value: T, next: Option<Box<Node<T>>>, } impl<T> Node<T> { fn new(value: T, next: Option<Box<Node<T>>>) -> Node<T> { Node { value: value, next: next } } } pub struct Stack<T> { first: Option<Box<Node<T>>>, n: usize, } /// A stack imp...
} assert_eq!(s.pop(), None); } }
random_line_split
stack.rs
//! Algorithm 1.2: Pushdown stack. struct Node<T> { value: T, next: Option<Box<Node<T>>>, } impl<T> Node<T> { fn
(value: T, next: Option<Box<Node<T>>>) -> Node<T> { Node { value: value, next: next } } } pub struct Stack<T> { first: Option<Box<Node<T>>>, n: usize, } /// A stack implementation based on a linked list. impl <T> Stack<T> { /// Constructs a new, empty stack. pub fn new() -> Stack<T> { ...
new
identifier_name
stack.rs
//! Algorithm 1.2: Pushdown stack. struct Node<T> { value: T, next: Option<Box<Node<T>>>, } impl<T> Node<T> { fn new(value: T, next: Option<Box<Node<T>>>) -> Node<T> { Node { value: value, next: next } } } pub struct Stack<T> { first: Option<Box<Node<T>>>, n: usize, } /// A stack imp...
}
{ let mut s = Stack::new(); for i in 0..10 { s.push(i); } for i in 0..10 { assert_eq!(s.pop(), Some(9 - i)); } assert_eq!(s.pop(), None); }
identifier_body
kqueue.rs
use {io, EventSet, PollOpt, Token}; use event::IoEvent; use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent}; use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT}; use std::{fmt, slice}; use std::os::unix::io::RawFd; use std::collections::H...
(&mut self) { self.events.clear(); self.event_map.clear(); for e in self.sys_events.iter() { let token = Token(e.udata as usize); let len = self.events.len(); let idx = *self.event_map.entry(token) .or_insert(len); if idx == len {...
coalesce
identifier_name
kqueue.rs
use {io, EventSet, PollOpt, Token}; use event::IoEvent; use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent}; use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT}; use std::{fmt, slice}; use std::os::unix::io::RawFd; use std::collections::H...
pub fn coalesce(&mut self) { self.events.clear(); self.event_map.clear(); for e in self.sys_events.iter() { let token = Token(e.udata as usize); let len = self.events.len(); let idx = *self.event_map.entry(token) .or_insert(len); ...
{ self.events[idx] }
identifier_body
kqueue.rs
use {io, EventSet, PollOpt, Token}; use event::IoEvent; use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent}; use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT}; use std::{fmt, slice}; use std::os::unix::io::RawFd; use std::collections::H...
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> { let cnt = try!(kevent(self.kq, &[], evts.as_mut_slice(), timeout_ms) .map_err(super::from_nix_error)); self.changes.sys_events.clear(); unsafe { evts.sys_events....
kq: try!(kqueue().map_err(super::from_nix_error)), changes: Events::new() }) }
random_line_split
kqueue.rs
use {io, EventSet, PollOpt, Token}; use event::IoEvent; use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent}; use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT}; use std::{fmt, slice}; use std::os::unix::io::RawFd; use std::collections::H...
if opts.contains(PollOpt::oneshot()) { flags = flags | EV_ONESHOT; } self.ev_push(fd, token, filter, flags); } fn ev_push(&mut self, fd: RawFd, token: usize, filter: EventFilter, flags: EventFlag) { self.changes.sys_events.push( KEvent { ...
{ flags = flags | EV_CLEAR; }
conditional_block
bitmap_font.rs
use render::TextureRegion; use image::{RgbaImage, Rgba}; use {load_file_contents}; use aphid::HashMap; use std::path::{PathBuf, Path}; use std::io; use std::ops::Range; use rusttype::{self, FontCollection, Scale, Font, point}; use std::fmt; #[derive(Debug, Clone)] pub struct FontDirectory { pub path: PathB...
} } return Some(texture_size) } None } pub fn build_font(full_path: &Path, font_description: &FontDescription, image_size: u32) -> Result<LoadedBitmapFont, FontLoadError> { let font_data = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path....
{ if bb.width() + at_x > texture_size as i32 { at_x = PADDING; at_y += pixel_height + PADDING; } if at_y + pixel_height >= texture_size as i32 - PADDING { continue 'sizes; ...
conditional_block
bitmap_font.rs
use render::TextureRegion; use image::{RgbaImage, Rgba}; use {load_file_contents}; use aphid::HashMap; use std::path::{PathBuf, Path}; use std::io; use std::ops::Range; use rusttype::{self, FontCollection, Scale, Font, point}; use std::fmt; #[derive(Debug, Clone)] pub struct FontDirectory { pub path: PathBu...
impl fmt::Debug for LoadedBitmapFont { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "LoadedBitmapFont {{ image: {:?} font: {:?} }}", self.image.dimensions(), self.font) } } pub struct BitmapFont { pub description: FontDescription, pub glyphs: HashMap<char, BitmapGlyph>, ...
pub image: RgbaImage, pub font: BitmapFont, }
random_line_split
bitmap_font.rs
use render::TextureRegion; use image::{RgbaImage, Rgba}; use {load_file_contents}; use aphid::HashMap; use std::path::{PathBuf, Path}; use std::io; use std::ops::Range; use rusttype::{self, FontCollection, Scale, Font, point}; use std::fmt; #[derive(Debug, Clone)] pub struct FontDirectory { pub path: PathB...
(font: &Font, chars: &Vec<char>, pixel_size: u32) -> Option<u32> { let scale = Scale { x: pixel_size as f32, y: pixel_size as f32 }; let v_metrics = font.v_metrics(scale); let offset = point(0.0, v_metrics.ascent); let pixel_height = scale.y.ceil() as i32; 'sizes: for n in 8..14 { // exclusive, 256 ...
min_square_texture_size
identifier_name
bitmap_font.rs
use render::TextureRegion; use image::{RgbaImage, Rgba}; use {load_file_contents}; use aphid::HashMap; use std::path::{PathBuf, Path}; use std::io; use std::ops::Range; use rusttype::{self, FontCollection, Scale, Font, point}; use std::fmt; #[derive(Debug, Clone)] pub struct FontDirectory { pub path: PathB...
} #[derive(Debug)] pub enum FontLoadError { CouldntLoadFile(PathBuf, io::Error), CouldntReadAsFont(PathBuf), TextureSizeTooSmall { requested: u32, required: Option<u32> }, What, } const PADDING: i32 = 2; pub fn min_square_texture_size(font: &Font, chars: &Vec<char>, pixel_size: u32) -> Option<u32> {...
{ write!(f, "BitmapFont {{ description: {:?} glyphs: {:?} kerning: {:?} }}", self.description, self.glyphs, self.kerning) }
identifier_body
removing-extern-crate.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() {}
main
identifier_name
removing-extern-crate.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{}
identifier_body
removing-extern-crate.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
extern crate removing_extern_crate as foo; extern crate core; mod another { extern crate removing_extern_crate as foo; extern crate core; } fn main() {}
#![allow(unused_imports)]
random_line_split
uniq.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } pub fn duplicate(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result { let _icx = push_ctxt("uniq::duplicate"); // Load the body of the source (*src) let src_datum = immediate_rvalue(src_box, src_ty); let body_datum = src_datum.box_body(bcx); // Malloc space in exchange heap and copy...
{ glue::trans_exchange_free(bcx, box_datum.val) }
conditional_block
uniq.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 ...
(bcx: block, vptrptr: ValueRef, box_ty: ty::t) -> block { let _icx = push_ctxt("uniq::make_free_glue"); let box_datum = immediate_rvalue(Load(bcx, vptrptr), box_ty); let not_null = IsNotNull(bcx, box_datum.val); do with_cond(bcx, not_null) |bcx| { let body_datum = box_datum.box_body(bcx); ...
make_free_glue
identifier_name
uniq.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 ...
} = malloc_unique(bcx, body_datum.ty); body_datum.copy_to(bcx, datum::INIT, dst_body); rslt(bcx, dst_box) }
random_line_split
uniq.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn duplicate(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result { let _icx = push_ctxt("uniq::duplicate"); // Load the body of the source (*src) let src_datum = immediate_rvalue(src_box, src_ty); let body_datum = src_datum.box_body(bcx); // Malloc space in exchange heap and copy src int...
{ let _icx = push_ctxt("uniq::make_free_glue"); let box_datum = immediate_rvalue(Load(bcx, vptrptr), box_ty); let not_null = IsNotNull(bcx, box_datum.val); do with_cond(bcx, not_null) |bcx| { let body_datum = box_datum.box_body(bcx); let bcx = glue::drop_ty(bcx, body_datum.to_ref_llval(...
identifier_body
brotli.rs
use super::{Format, Quality, App, SubCommand, ArgMatches, Arg, Operation, Comp, File, PathBuf, get_comp_level, valid_item, item_exists}; pub fn build<'a>() -> App<'static, 'a> { SubCommand::with_name("brotli") .about("Create a tar file with brotli compression") .arg( Arg::with...
.help("what to tar"), ) .arg( Arg::with_name("output") .short("o") .long("out") .takes_value(true) .multiple(false) .value_name("OUTFILE") .required(true) .validator(item_ex...
.next_line_help(true) .global(true)
random_line_split
brotli.rs
use super::{Format, Quality, App, SubCommand, ArgMatches, Arg, Operation, Comp, File, PathBuf, get_comp_level, valid_item, item_exists}; pub fn build<'a>() -> App<'static, 'a> { SubCommand::with_name("brotli") .about("Create a tar file with brotli compression") .arg( Arg::with...
}, x.values_of("file").unwrap().map(PathBuf::from).collect(), ) }
{ Operation::Create( { let path = x.value_of("output").unwrap(); let w = match File::create(&path) { Ok(x) => x, Err(e) => { println!("Could not create output {}", &path); println!("Error {:?}", e); ...
identifier_body
brotli.rs
use super::{Format, Quality, App, SubCommand, ArgMatches, Arg, Operation, Comp, File, PathBuf, get_comp_level, valid_item, item_exists}; pub fn
<'a>() -> App<'static, 'a> { SubCommand::with_name("brotli") .about("Create a tar file with brotli compression") .arg( Arg::with_name("file") .short("f") .long("file") .takes_value(true) .multiple(true) .value_name(...
build
identifier_name
color.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("Color", inherited=True) %> <% fr...
} % endif
random_line_split
lookup.rs
// // Copyright 2021 The Project Oak Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
None => { extension .logger .log_sensitive(Level::Debug, "storage_get_item(): value not found"); Err(OakStatus::ErrStorageItemNotFound) } } } impl OakApiNativeExtension for LookupExtension { fn invoke( &mut self, wasm_state: ...
random_line_split
lookup.rs
// // Copyright 2021 The Project Oak Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
( &mut self, wasm_state: &mut WasmState, args: wasmi::RuntimeArgs, ) -> Result<Result<(), OakStatus>, wasmi::Trap> { Ok(storage_get_item( wasm_state, self, args.nth_checked(0)?, args.nth_checked(1)?, args.nth_checked(2)?, ...
invoke
identifier_name
lookup.rs
// // Copyright 2021 The Project Oak Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
}
{ Ok(()) }
identifier_body
lookup.rs
// // Copyright 2021 The Project Oak Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
} } impl OakApiNativeExtension for LookupExtension { fn invoke( &mut self, wasm_state: &mut WasmState, args: wasmi::RuntimeArgs, ) -> Result<Result<(), OakStatus>, wasmi::Trap> { Ok(storage_get_item( wasm_state, self, args.nth_checked(0)?...
{ extension .logger .log_sensitive(Level::Debug, "storage_get_item(): value not found"); Err(OakStatus::ErrStorageItemNotFound) }
conditional_block
model.rs
use std::collections::HashMap; use itertools::Itertools; use rustc_serialize::json; use ngrams::ngrams; use errors::DeserializeError; pub struct Model { pub ngram_ranks: HashMap<String, usize>, } impl Model { pub fn build_from_text(text: &str) -> Self { let mut ngram_counts = HashMap::new(); ...
ngram_counts.insert(ngram.to_owned(), 1); } } } let ngrams = ngram_counts .into_iter() .sorted_by(|a, b| Ord::cmp(&b.1, &a.1)) .into_iter() .take(300) // Models need to have the same size, or have normalized "...
{ *count += 1; continue; }
conditional_block
model.rs
use std::collections::HashMap; use itertools::Itertools; use rustc_serialize::json; use ngrams::ngrams; use errors::DeserializeError; pub struct Model { pub ngram_ranks: HashMap<String, usize>, } impl Model { pub fn build_from_text(text: &str) -> Self { let mut ngram_counts = HashMap::new(); ...
(bytes: Vec<u8>) -> Result<Self, DeserializeError> { let string = try!(String::from_utf8(bytes)); let ngram_ranks = try!(json::decode(string.as_str())); let model = Model { ngram_ranks: ngram_ranks }; Ok(model) } pub fn serialize(&self) -> Vec<u8> { json::encode(&self.ng...
deserialize
identifier_name
model.rs
use std::collections::HashMap; use itertools::Itertools; use rustc_serialize::json; use ngrams::ngrams; use errors::DeserializeError; pub struct Model { pub ngram_ranks: HashMap<String, usize>, } impl Model { pub fn build_from_text(text: &str) -> Self { let mut ngram_counts = HashMap::new(); ...
let serialized = model.serialize(); let deserialized = Model::deserialize(serialized).unwrap(); assert_eq!(model.ngram_ranks, deserialized.ngram_ranks); } }
random_line_split
inventory_vector.rs
use Encode; #[derive(Debug, Default, Encode, PartialEq)] pub struct
{ flags: InvFlags, pub hash: [u8; 32], } bitflags! { #[derive(Default, Encode)] flags InvFlags: u32 { const ERROR = 0b0, const MSG_TX = 0b00000001, const MSG_BLOCK = 0b00000010, const MSG_FILTERED_BLOCK = 0b00000100, const MSG_CMPCT_BLOCK...
InventoryVector
identifier_name
inventory_vector.rs
use Encode; #[derive(Debug, Default, Encode, PartialEq)] pub struct InventoryVector { flags: InvFlags, pub hash: [u8; 32], } bitflags! { #[derive(Default, Encode)]
flags InvFlags: u32 { const ERROR = 0b0, const MSG_TX = 0b00000001, const MSG_BLOCK = 0b00000010, const MSG_FILTERED_BLOCK = 0b00000100, const MSG_CMPCT_BLOCK = 0b00001000 } } impl InventoryVector { pub fn new(flags: u32, hash: &[u8]) -> I...
random_line_split
either.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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 later ver...
<L, R> { Left(L), Right(R) } impl<L, R> Either<L, R> { }
Either
identifier_name
either.rs
// Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos. // // Serkr 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 later ver...
} impl<L, R> Either<L, R> { }
#[derive(Debug)] #[allow(missing_docs)] pub enum Either<L, R> { Left(L), Right(R)
random_line_split
script_msg.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 AnimationState; use AuxiliaryBrowsingContextLoadInfo; use DocumentState; use IFrameLoadInfo; use IFrameLoadInf...
CreateCanvasPaintThread(..) => "CreateCanvasPaintThread", Focus => "Focus", GetClipboardContents(..) => "GetClipboardContents", GetBrowsingContextInfo(..) => "GetBrowsingContextInfo", GetTopForBrowsingContext(..) => "GetParentBrowsingContext", GetC...
InitiateNavigateRequest(..) => "InitiateNavigateRequest", BroadcastStorageEvent(..) => "BroadcastStorageEvent", ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
random_line_split
script_msg.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 AnimationState; use AuxiliaryBrowsingContextLoadInfo; use DocumentState; use IFrameLoadInfo; use IFrameLoadInf...
{ /// Indicates whether this pipeline is currently running animations. ChangeRunningAnimationsState(PipelineId, AnimationState), /// Inform the constellation of the size of the iframe's viewport. IFrameSizes(Vec<(BrowsingContextId, TypedSize2D<f32, CSSPixel>)>), /// Requests that the constellation ...
LayoutMsg
identifier_name
main.rs
use std::thread; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right ...
let handles: Vec<_> = philosophers.into_iter().map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); })}).collect(); for h in handles { h.join().unwrap(); } }
// 0, 4 rather than 4, 0 to avoid deadlock Philosopher::new("Michel Foucault", 0, 4)];
random_line_split
main.rs
use std::thread; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize } impl Philosopher { fn
(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right } } fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); let _right = table.forks[self.right]...
new
identifier_name
engine.rs
use libc::{c_int, c_uint, c_ulonglong, size_t}; use ffi::{core, target}; use ffi::execution_engine as engine; use ffi::execution_engine::*; use ffi::target_machine::LLVMCodeModel; use cbox::CBox; use std::marker::PhantomData; use std::{mem, ptr}; use std::ops::*; use compile::Compile; use context::{Context, GetContext}...
/// Maps a global to a specific memory location. unsafe fn add_global_mapping<T>(&'b self, global: &'a Value, addr: *const T) { engine::LLVMAddGlobalMapping(self.into(), global.into(), mem::transmute(addr)); } } /// The options to pass to the MCJIT backend. #[derive(Copy, Clone)] pub struct JitOpt...
{ util::with_cstr(name, |ptr| mem::transmute(engine::LLVMGetGlobalValueAddress(self.into(), ptr)) ) }
identifier_body
engine.rs
use libc::{c_int, c_uint, c_ulonglong, size_t}; use ffi::{core, target}; use ffi::execution_engine as engine; use ffi::execution_engine::*; use ffi::target_machine::LLVMCodeModel; use cbox::CBox; use std::marker::PhantomData; use std::{mem, ptr}; use std::ops::*; use compile::Compile; use context::{Context, GetContext}...
fn add_module(&'b self, module: &'a Module) { unsafe { engine::LLVMAddModule(self.into(), (&*module).into()) } } /// Remove a module from the list of modules to interpret or compile. fn remove_module(&'b self, module: &'a Module) -> &'a Module { unsafe { let mut out = mem::un...
/// Create a new execution engine with the given `Module` and options, or return a /// description of the error. fn new(module: &'a Module, options: Self::Options) -> Result<Self, CBox<str>>; /// Add a module to the list of modules to interpret or compile.
random_line_split
engine.rs
use libc::{c_int, c_uint, c_ulonglong, size_t}; use ffi::{core, target}; use ffi::execution_engine as engine; use ffi::execution_engine::*; use ffi::target_machine::LLVMCodeModel; use cbox::CBox; use std::marker::PhantomData; use std::{mem, ptr}; use std::ops::*; use compile::Compile; use context::{Context, GetContext}...
else if nparams == 0 { assert_eq!(arg, Type::get::<()>(ctx)); } else { panic!("array type arguments are not yet supported; use a tuple or struct instead"); } } } unsafe { cb(self.get_function::<A, R>(functio...
{ assert_eq!(arg, sig.get_params()[0]); }
conditional_block
engine.rs
use libc::{c_int, c_uint, c_ulonglong, size_t}; use ffi::{core, target}; use ffi::execution_engine as engine; use ffi::execution_engine::*; use ffi::target_machine::LLVMCodeModel; use cbox::CBox; use std::marker::PhantomData; use std::{mem, ptr}; use std::ops::*; use compile::Compile; use context::{Context, GetContext}...
(value: GenericValue<'a>, _: &'a Context) -> bool { unsafe { engine::LLVMGenericValueToInt(value.into(), 0)!= 0 } } } generic_int!{some i8, u8} generic_int!{some i16, u16} generic_int!{some i32, u32} generic_int!{some i64, u64}
from_generic
identifier_name
main.rs
#[macro_use] extern crate scad_generator; extern crate scad_util as su; use scad_generator::*; fn ir_screwholes(depth: f32) -> ScadObject { let screw_distance = 38.; let screw_diameter = 4.; //TODO add nut let screwhole = scad!(Cylinder(depth, Diameter(screw_diameter))); let translated = scad!(T...
sfile.write_to_file(String::from("out.scad")); }
random_line_split
main.rs
#[macro_use] extern crate scad_generator; extern crate scad_util as su; use scad_generator::*; fn ir_screwholes(depth: f32) -> ScadObject
pub fn main() { let mut sfile = ScadFile::new(); sfile.set_detail(50); sfile.add_object(ir_screwholes(10.)); //Save the scad code to a file sfile.write_to_file(String::from("out.scad")); }
{ let screw_distance = 38.; let screw_diameter = 4.; //TODO add nut let screwhole = scad!(Cylinder(depth, Diameter(screw_diameter))); let translated = scad!(Translate(vec3(screw_distance, 0., 0.));screwhole); scad!(Union; { translated.clone(), scad!(Mirror(vec3(1., 0., 0.)...
identifier_body
main.rs
#[macro_use] extern crate scad_generator; extern crate scad_util as su; use scad_generator::*; fn ir_screwholes(depth: f32) -> ScadObject { let screw_distance = 38.; let screw_diameter = 4.; //TODO add nut let screwhole = scad!(Cylinder(depth, Diameter(screw_diameter))); let translated = scad!(T...
() { let mut sfile = ScadFile::new(); sfile.set_detail(50); sfile.add_object(ir_screwholes(10.)); //Save the scad code to a file sfile.write_to_file(String::from("out.scad")); }
main
identifier_name
backtrace.rs
in theory means that they're available for dynamic /// linking and lookup. Other symbols end up only in the local symbol table of /// the file. This loosely corresponds to pub and priv functions in Rust. /// /// Armed with this knowledge, we know that our solution for address to symbol /// translation will need to con...
// pointer points *outside* of the calling function, and by // unwinding it we go back to the original function. let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") { ip } else { unsafe { uw::_Unwind_FindEnclosingFunction(ip) } }; ...
{ let cx: &mut Context = unsafe { mem::transmute(arg) }; let mut ip_before_insn = 0; let mut ip = unsafe { uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void }; if !ip.is_null() && ip_before_insn == 0 { // this is a non-signaling frame, s...
identifier_body
backtrace.rs
which in theory means that they're available for dynamic /// linking and lookup. Other symbols end up only in the local symbol table of /// the file. This loosely corresponds to pub and priv functions in Rust. /// /// Armed with this knowledge, we know that our solution for address to symbol /// translation will need ...
/// semi-reasonable solution. The stdlib already knows how to spawn processes, /// so in theory it could invoke readelf, parse the output, and consult the /// local/dynamic symbol tables from there. This ended up not getting chosen /// due to the craziness of the idea plus the advent of the next option. /// ///...
random_line_split
backtrace.rs
in theory means that they're available for dynamic /// linking and lookup. Other symbols end up only in the local symbol table of /// the file. This loosely corresponds to pub and priv functions in Rust. /// /// Armed with this knowledge, we know that our solution for address to symbol /// translation will need to con...
(data: *mut libc::c_void, _pc: libc::uintptr_t, filename: *const libc::c_char, lineno: libc::c_int, _function: *const libc::c_char) -> libc::c_int { if!filename.is_null() { let slot = data as *mut &mut [F...
pcinfo_cb
identifier_name
backtrace.rs
in theory means that they're available for dynamic /// linking and lookup. Other symbols end up only in the local symbol table of /// the file. This loosely corresponds to pub and priv functions in Rust. /// /// Armed with this knowledge, we know that our solution for address to symbol /// translation will need to con...
// just to be sure let file = unsafe { CStr::from_ptr(file).to_bytes() }; try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1)); } } Ok(()) } // Finally, after all that work above, we can emit a symbol. fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void, ...
{ continue; }
conditional_block
main.rs
use std::thread; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, ...
(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); let _right = table.forks[self.right].lock().unwrap(); println!("{} is eating.", self.name); thread::sleep_ms(1000); println!("{} is done eating.", self.name); } } struct Table { forks: Vec<Mu...
eat
identifier_name
main.rs
use std::thread; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, ...
} struct Table { forks: Vec<Mutex<()>>, } fn main() { let table = Arc::new(Table { forks: vec![ Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), ]}); let philosophers = vec![ Philosopher::new("Baruch Spinoza", 0, 1), ...
{ let _left = table.forks[self.left].lock().unwrap(); let _right = table.forks[self.right].lock().unwrap(); println!("{} is eating.", self.name); thread::sleep_ms(1000); println!("{} is done eating.", self.name); }
identifier_body
main.rs
use std::thread; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, ...
Philosopher::new("Michel Foucault", 0, 4), ]; let handles: Vec<_> = philosophers.into_iter().map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }).collect(); for h in handles { h.join().unwrap(); } }
let philosophers = vec![ Philosopher::new("Baruch Spinoza", 0, 1), Philosopher::new("Gilles Deleuze", 1, 2), Philosopher::new("Karl Marx", 2, 3), Philosopher::new("Friedrich Nietzsche", 3, 4),
random_line_split
lib.rs
pub mod proto; use crate::proto::hello::{HelloReq, HelloResp}; use crate::proto::hello_grpc::HelloService; use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; #[derive(Clone)] pub struct GrpcHelloService; impl HelloService for GrpcHelloService { fn say_hello(&mut self, ctx: RpcCo...
else { let reply_msg = format!("Hey, {}!", name); let mut reply = HelloResp::new(); reply.set_Result(reply_msg); let f = sink .success(reply) .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); ctx.spawn(f); ...
{ let reply_msg = "Length of `Name` cannot be more than 10 characters"; let f = sink .fail(RpcStatus::new( RpcStatusCode::InvalidArgument, Some(reply_msg.to_string()), )) .map_err(move |e| println!("failed t...
conditional_block
lib.rs
pub mod proto; use crate::proto::hello::{HelloReq, HelloResp}; use crate::proto::hello_grpc::HelloService; use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; #[derive(Clone)] pub struct GrpcHelloService; impl HelloService for GrpcHelloService { fn
(&mut self, ctx: RpcContext, req: HelloReq, sink: UnarySink<HelloResp>) { let name = req.get_Name(); let reply_msg = format!("Hey, {}!", name); let mut reply = HelloResp::new(); reply.set_Result(reply_msg); let f = sink .success(reply) .map_err(move |e| pr...
say_hello
identifier_name
lib.rs
pub mod proto; use crate::proto::hello::{HelloReq, HelloResp}; use crate::proto::hello_grpc::HelloService; use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; #[derive(Clone)] pub struct GrpcHelloService; impl HelloService for GrpcHelloService { fn say_hello(&mut self, ctx: RpcCo...
Some(reply_msg.to_string()), )) .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); ctx.spawn(f); } else { let reply_msg = format!("Hey, {}!", name); let mut reply = HelloResp::new(); reply.set_Re...
.fail(RpcStatus::new( RpcStatusCode::InvalidArgument,
random_line_split
builtin-superkinds-self-type.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl <T: Send +'static> Foo for T { } pub fn main() { let (tx, rx) = channel(); 1193182.foo(tx); assert_eq!(rx.recv().unwrap(), 1193182); }
{ tx.send(self).unwrap(); }
identifier_body
builtin-superkinds-self-type.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 ...
trait Foo : Send + Sized +'static { fn foo(self, tx: Sender<Self>) { tx.send(self).unwrap(); } } impl <T: Send +'static> Foo for T { } pub fn main() { let (tx, rx) = channel(); 1193182.foo(tx); assert_eq!(rx.recv().unwrap(), 1193182); }
use std::sync::mpsc::{Sender, channel};
random_line_split
builtin-superkinds-self-type.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, tx: Sender<Self>) { tx.send(self).unwrap(); } } impl <T: Send +'static> Foo for T { } pub fn main() { let (tx, rx) = channel(); 1193182.foo(tx); assert_eq!(rx.recv().unwrap(), 1193182); }
foo
identifier_name
tree.rs
//! Generic Tree Implementation for Plan use std::rc::Rc; pub enum TreeBuildError { EmptyStack, StillRemainStackItem, } pub enum TreeNode<T> { Branch(T, Vec<Box<TreeNode<T>>>), Leaf(T), } #[allow(unused_variables)] pub trait Visitor<'v, T>: Sized { fn accept(&mut self, data: &'v T, child: Option<&'v Vec<B...
} #[cfg(test)] mod tests { use super::{TreeBuilder, TreeNode, Visitor}; pub struct TestVisitor; pub struct AA; impl<'v> Visitor<'v, AA> for TestVisitor { fn accept(&mut self, data: &AA, child: Option<&'v Vec<Box<TreeNode<AA>>>>) { self.accept_by_default(child); } } #[test] fn test_tree...
{ match self.stack.len() { 0 => Err(TreeBuildError::EmptyStack), 1 => Ok(self.stack.pop().unwrap()), _ => Err(TreeBuildError::StillRemainStackItem), } }
identifier_body
tree.rs
//! Generic Tree Implementation for Plan use std::rc::Rc; pub enum TreeBuildError { EmptyStack, StillRemainStackItem, } pub enum TreeNode<T> { Branch(T, Vec<Box<TreeNode<T>>>), Leaf(T), } #[allow(unused_variables)] pub trait Visitor<'v, T>: Sized { fn accept(&mut self, data: &'v T, child: Option<&'v Vec<B...
None => {} }; } } pub fn walk_tree<'v, V, T>(v: &mut V, node: &'v TreeNode<T>) where V: Visitor<'v, T> { match *node { TreeNode::Leaf(ref data) => v.accept(data, None), TreeNode::Branch(ref data, ref child) => v.accept(data, Some(child)), }; } pub type SimpleVisitor<T> = Rc<Fn(&T, Option<&V...
{ for node in v.iter().map(|n| &*n) { walk_tree(self, node); } }
conditional_block
tree.rs
//! Generic Tree Implementation for Plan use std::rc::Rc; pub enum TreeBuildError { EmptyStack, StillRemainStackItem, } pub enum TreeNode<T> { Branch(T, Vec<Box<TreeNode<T>>>), Leaf(T), } #[allow(unused_variables)] pub trait Visitor<'v, T>: Sized { fn accept(&mut self, data: &'v T, child: Option<&'v Vec<B...
pub struct AA; impl<'v> Visitor<'v, AA> for TestVisitor { fn accept(&mut self, data: &AA, child: Option<&'v Vec<Box<TreeNode<AA>>>>) { self.accept_by_default(child); } } #[test] fn test_tree() { let mut builder: TreeBuilder<&'static str> = TreeBuilder::new(); builder.push(TreeNode::L...
pub struct TestVisitor;
random_line_split
tree.rs
//! Generic Tree Implementation for Plan use std::rc::Rc; pub enum TreeBuildError { EmptyStack, StillRemainStackItem, } pub enum TreeNode<T> { Branch(T, Vec<Box<TreeNode<T>>>), Leaf(T), } #[allow(unused_variables)] pub trait Visitor<'v, T>: Sized { fn accept(&mut self, data: &'v T, child: Option<&'v Vec<B...
; impl<'v> Visitor<'v, AA> for TestVisitor { fn accept(&mut self, data: &AA, child: Option<&'v Vec<Box<TreeNode<AA>>>>) { self.accept_by_default(child); } } #[test] fn test_tree() { let mut builder: TreeBuilder<&'static str> = TreeBuilder::new(); builder.push(TreeNode::Leaf("l1")).ok();...
AA
identifier_name
mutable-class-fields.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 nyan : cat = cat(52, 99); nyan.how_hungry = 0; //[ast]~ ERROR cannot assign //[mir]~^ ERROR cannot assign }
random_line_split
mutable-class-fields.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 ...
(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y } } fn main() { let nyan : cat = cat(52, 99); nyan.how_hungry = 0; //[ast]~ ERROR cannot assign //[mir]~^ ERROR cannot assign }
cat
identifier_name
mutable-class-fields.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let nyan : cat = cat(52, 99); nyan.how_hungry = 0; //[ast]~ ERROR cannot assign //[mir]~^ ERROR cannot assign }
{ cat { meows: in_x, how_hungry: in_y } }
identifier_body
sequential.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/. */ //! Implements sequential traversals over the DOM and flow trees. use context::{LayoutContext, SharedLayoutContex...
}
{ fn doit(flow: &mut Flow, iterator: &mut FragmentBorderBoxIterator, stacking_context_position: &Point2D<Au>) { flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position); for kid in flow::mut_base(flow).child_iter() { let stacking_context_po...
identifier_body
sequential.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/. */ //! Implements sequential traversals over the DOM and flow trees. use context::{LayoutContext, SharedLayoutContex...
(node: LayoutNode, recalc_style: RecalcStyleForNode, construct_flows: ConstructFlows) { recalc_style.process(node); for kid in node.children() { doit(kid, recalc_style, construct_flows); } construct_flows.process(node); } let layout_context = LayoutContext::new(sh...
doit
identifier_name
sequential.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/. */ //! Implements sequential traversals over the DOM and flow trees. use context::{LayoutContext, SharedLayoutContex...
if build_display_list.should_process(flow) { build_display_list.process(flow); } } let layout_context = LayoutContext::new(shared_layout_context); let compute_absolute_positions = ComputeAbsolutePositions { layout_context: &layout_context }; let build_display_list =...
} for kid in flow::mut_base(flow).child_iter() { doit(kid, compute_absolute_positions, build_display_list); }
random_line_split
sequential.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/. */ //! Implements sequential traversals over the DOM and flow trees. use context::{LayoutContext, SharedLayoutContex...
for kid in flow::child_iter(flow) { doit(kid, assign_inline_sizes, assign_block_sizes); } if assign_block_sizes.should_process(flow) { assign_block_sizes.process(flow); } } let layout_context = LayoutContext::new(shared_layout_context); let root =...
{ assign_inline_sizes.process(flow); }
conditional_block
lib.rs
use std::process::{Command, Stdio}; use std::collections::HashSet; use std::thread; struct ProcessSets { prev_set: HashSet<Process>, curr_set: HashSet<Process>, } #[derive(PartialEq, Eq, Clone, Hash)] pub struct Process { pub pid: u32, pub description: String, } pub trait ProcessWatcherCallback : Sen...
Err(_) => continue, }; fields.next(); fields.next(); let desc : String = fields.next().unwrap().to_owned(); //filtering processes opened by calling "/bin/ps" if desc.ne("/bin/ps") { sets.curr_set.insert(Process { p...
random_line_split
lib.rs
use std::process::{Command, Stdio}; use std::collections::HashSet; use std::thread; struct ProcessSets { prev_set: HashSet<Process>, curr_set: HashSet<Process>, } #[derive(PartialEq, Eq, Clone, Hash)] pub struct Process { pub pid: u32, pub description: String, } pub trait ProcessWatcherCallback : Sen...
sets.prev_set = sets.curr_set.clone(); sets.curr_set.clear(); return (open_set, closed_set); } pub fn watch_with_callback<TCallback :'static + ProcessWatcherCallback>(callback: TCallback) { let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() }; thread::spawn( move ||...
{ open_set = sets.curr_set.difference(&sets.prev_set).cloned().collect(); closed_set = sets.prev_set.difference(&sets.curr_set).cloned().collect(); }
conditional_block
lib.rs
use std::process::{Command, Stdio}; use std::collections::HashSet; use std::thread; struct ProcessSets { prev_set: HashSet<Process>, curr_set: HashSet<Process>, } #[derive(PartialEq, Eq, Clone, Hash)] pub struct Process { pub pid: u32, pub description: String, } pub trait ProcessWatcherCallback : Sen...
<F, G>(on_open: F, on_close: G) where F :'static + Fn(Process) + Send, G :'static + Fn(Process) + Send { let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() }; thread::spawn( move || { loop { let changed_sets = get_processes(&mut sets); ...
watch_with_closure
identifier_name
client.rs
//! Handle network connections for a varlink service #![allow(dead_code)] use std::net::TcpStream; #[cfg(unix)] use std::os::unix::io::{AsRawFd, IntoRawFd}; #[cfg(unix)] use std::os::unix::net::UnixStream; use std::process::Child; #[cfg(unix)] use libc::{close, dup2, getpid}; use tempfile::TempDir; #[cfg(windows)] u...
{ use std::os::unix::io::FromRawFd; use std::process::Command; let executable = address.as_ref(); // use unix_socket::UnixStream; let (stream0, stream1) = UnixStream::pair().map_err(map_context!())?; let fd = stream1.into_raw_fd(); let childin = unsafe { ::std::fs::File::from_raw_fd(fd) }; ...
identifier_body
client.rs
//! Handle network connections for a varlink service #![allow(dead_code)] use std::net::TcpStream; #[cfg(unix)] use std::os::unix::io::{AsRawFd, IntoRawFd}; #[cfg(unix)] use std::os::unix::net::UnixStream; use std::process::Child; #[cfg(unix)] use libc::{close, dup2, getpid}; use tempfile::TempDir; #[cfg(windows)] u...
(_addr: &str) -> Result<UnixStream> { Err(context!(ErrorKind::InvalidAddress)) } #[cfg(windows)] pub fn varlink_exec<S:?Sized + AsRef<str>>( _address: &S, ) -> Result<(Child, String, Option<TempDir>)> { Err(context!(ErrorKind::MethodNotImplemented( "varlink_exec".into() ))) } #[cfg(unix)] pub ...
get_abstract_unixstream
identifier_name
client.rs
//! Handle network connections for a varlink service #![allow(dead_code)] use std::net::TcpStream; #[cfg(unix)] use std::os::unix::io::{AsRawFd, IntoRawFd}; #[cfg(unix)] use std::os::unix::net::UnixStream; use std::process::Child; #[cfg(unix)] use libc::{close, dup2, getpid}; use tempfile::TempDir; #[cfg(windows)] u...
} else { Err(context!(ErrorKind::InvalidAddress))? } } #[cfg(any(target_os = "linux", target_os = "android"))] fn get_abstract_unixstream(addr: &str) -> Result<UnixStream> { // FIXME: abstract unix domains sockets still not in std // FIXME: https://github.com/rust-lang/rust/issues/14194 use...
Box::new(UnixStream::connect(addr).map_err(map_context!())?), new_address, ))
random_line_split