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
pixel_ops.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use librsvg::surface_utils::{Pixel, PixelOps}; const OTHER: Pixel = Pixel {
g: 0x20, b: 0x30, a: 0x40, }; const N: usize = 1024; fn make_pixels(n: usize) -> Vec<Pixel> { (0..n) .map(|i| Pixel { r: (i / 2) as u8, g: (i / 3) as u8, b: (i / 4) as u8, a: i as u8, }) .collect() } fn bench_op<F>(pixels: &[Pixel],...
r: 0x10,
random_line_split
main.rs
#[macro_use] extern crate clap; mod reader; use reader::excel; use reader::csv; use std::io::Write; use std::path::PathBuf; use clap::{Arg, App}; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ...
() { let matches = App::new("xcat") .version(crate_version!()) .author(crate_authors!()) .about("Expanded cat tool especially for Excel") .arg(Arg::with_name("delimiter") .help("Delimiter for csv file") .short("d") .long("delimiter") .value...
main
identifier_name
main.rs
#[macro_use] extern crate clap; mod reader; use reader::excel; use reader::csv; use std::io::Write; use std::path::PathBuf; use clap::{Arg, App}; macro_rules! println_stderr( ($($arg:tt)*) => { { let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ...
let files: Vec<_> = matches.values_of("input_files").unwrap().collect(); for file in files { let sce = PathBuf::from(&file); if!sce.exists() { println_stderr!("{}: No such file or directory", file); continue; } match sce.extension().and_then(|s| s.to_str()...
{ let matches = App::new("xcat") .version(crate_version!()) .author(crate_authors!()) .about("Expanded cat tool especially for Excel") .arg(Arg::with_name("delimiter") .help("Delimiter for csv file") .short("d") .long("delimiter") ....
identifier_body
main.rs
#[macro_use] extern crate clap; mod reader; use reader::excel; use reader::csv; use std::io::Write; use std::path::PathBuf;
let r = writeln!(&mut ::std::io::stderr(), $($arg)*); r.expect("failed printing to stderr"); } } ); fn main() { let matches = App::new("xcat") .version(crate_version!()) .author(crate_authors!()) .about("Expanded cat tool especially for Excel") .arg(Arg::with_name("...
use clap::{Arg, App}; macro_rules! println_stderr( ($($arg:tt)*) => { {
random_line_split
memory_pool.rs
use std::cell::UnsafeCell; use std::mem; use poolable::Poolable; thread_local!( static POOL: UnsafeCell< MemoryPool > = UnsafeCell::new( MemoryPool::new() ) ); struct MemoryPool { buffers: Vec< (*mut u8, usize) > } impl MemoryPool { fn new() -> MemoryPool { MemoryPool { buffers: Vec::new...
<F, T, R>( callback: F ) -> R where F: FnOnce( &mut T ) -> R, T: Poolable { let mut result = None; with_pool( |pool| { result = Some( pool.borrow( callback ) ); }); result.unwrap() } #[cfg(test)] mod tests { mod memory_pool { pub use super::super::*; } #[test] fn borro...
borrow
identifier_name
memory_pool.rs
use std::cell::UnsafeCell; use std::mem; use poolable::Poolable; thread_local!( static POOL: UnsafeCell< MemoryPool > = UnsafeCell::new( MemoryPool::new() ) ); struct MemoryPool { buffers: Vec< (*mut u8, usize) > } impl MemoryPool { fn new() -> MemoryPool { MemoryPool { buffers: Vec::new...
} } #[inline] fn borrow<T, F, R>( &mut self, callback: F ) -> R where F: FnOnce( &mut T ) -> R, T: Poolable { let mut value = self.acquire::<T>(); let result = callback( &mut value ); self.release::<T>( value ); result } } impl Drop for MemoryPool { fn dro...
{ mem::forget( value ); self.buffers.push( (ptr, capacity) ); }
conditional_block
memory_pool.rs
use std::cell::UnsafeCell; use std::mem; use poolable::Poolable; thread_local!( static POOL: UnsafeCell< MemoryPool > = UnsafeCell::new( MemoryPool::new() ) ); struct MemoryPool { buffers: Vec< (*mut u8, usize) > } impl MemoryPool { fn new() -> MemoryPool
#[inline] fn acquire<T>( &mut self ) -> T where T: Poolable { match self.buffers.pop() { None => T::empty(), Some( (ptr, capacity) ) => unsafe { T::from_buffer( ptr, capacity ) } } } #[inline] fn release<T>( &mut self, mut value: T ) where T: Poolable { ...
{ MemoryPool { buffers: Vec::new() } }
identifier_body
memory_pool.rs
use std::cell::UnsafeCell; use std::mem; use poolable::Poolable; thread_local!( static POOL: UnsafeCell< MemoryPool > = UnsafeCell::new( MemoryPool::new() ) ); struct MemoryPool { buffers: Vec< (*mut u8, usize) > } impl MemoryPool { fn new() -> MemoryPool { MemoryPool { buffers: Vec::new...
result.unwrap() } #[cfg(test)] mod tests { mod memory_pool { pub use super::super::*; } #[test] fn borrow_string() { memory_pool::borrow( |aux: &mut String| { // We should get a clean buffer at first. assert_eq!( aux.len(), 0 ); assert_eq!( aux.c...
random_line_split
nodemap.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 ...
/// libcollections by default uses SipHash which isn't quite as speedy as we /// want. In the compiler we're not really worried about DOS attempts, so we /// just default to a non-cryptographic hash. /// /// This uses FNV hashing, as described here: /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_f...
pub fn NodeSet() -> NodeSet { FnvHashSet() } pub fn DefIdSet() -> DefIdSet { FnvHashSet() } /// A speedy hash algorithm for node ids and def ids. The hashmap in
random_line_split
nodemap.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 ...
<T>() -> NodeMap<T> { FnvHashMap() } pub fn DefIdMap<T>() -> DefIdMap<T> { FnvHashMap() } pub fn NodeSet() -> NodeSet { FnvHashSet() } pub fn DefIdSet() -> DefIdSet { FnvHashSet() } /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn't quite as spee...
NodeMap
identifier_name
nodemap.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 NodeMap<T>() -> NodeMap<T> { FnvHashMap() } pub fn DefIdMap<T>() -> DefIdMap<T> { FnvHashMap() } pub fn NodeSet() -> NodeSet { FnvHashSet() } pub fn DefIdSet() -> DefIdSet { FnvHashSet() } /// A speedy hash algorithm for node ids and def ids. The hashmap in /// libcollections by default uses SipHash which isn...
{ Default::default() }
identifier_body
main.rs
extern crate nemo; #[macro_use] extern crate clap; extern crate bounded_spsc_queue as queue; use std::io::{stdin, stdout, Write}; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::io; use std::io::prelude::*; use std::fs::File; use std::thread; use clap::{Arg, App}; fn main() { let matches = App::new("...
loop { let lock = c.lock().unwrap(); match lock.try_pop() { Some(_) => {}, None => thread::sleep_ms(200), } } }); println!("><> nemo v{} <><", crate_version!()); println!("Use Ctrl-C to exit."); loop { print!("> ...
{ let env = nemo::interpreter::initial_enviroment(); let stdin = stdin(); let mut stdout = stdout(); let (repl_producer, consumer) = queue::make(1); let (repl_producer, consumer) = (Arc::new(Mutex::new(repl_producer)), Arc::new(Mutex::new(consumer))); let (producer, repl_consumer) = queue::make(...
identifier_body
main.rs
extern crate nemo; #[macro_use] extern crate clap; extern crate bounded_spsc_queue as queue; use std::io::{stdin, stdout, Write}; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::io; use std::io::prelude::*; use std::fs::File; use std::thread; use clap::{Arg, App}; fn main() { let matches = App::new("...
lock.borrow_mut().set(name, Some(nemo::interpreter::Value::Module(module_env))); } else { let expr = match nemo::parser::parse_Expr(&input) { Ok(expr) => expr, Err(e) => { println!("Error: {:?}", e); continue; ...
let name = ::std::path::Path::new(&module_path).file_stem().unwrap().to_str().unwrap().to_owned(); let lock = env.lock().unwrap();
random_line_split
main.rs
extern crate nemo; #[macro_use] extern crate clap; extern crate bounded_spsc_queue as queue; use std::io::{stdin, stdout, Write}; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::io; use std::io::prelude::*; use std::fs::File; use std::thread; use clap::{Arg, App}; fn main() { let matches = App::new("...
else if let Ok(nemo::ast::Top::Use(module_path)) = nemo::parser::parse_Use(&input) { let mut file = File::open(&module_path).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let module_env = nemo::interpreter::initial_enviroment();...
{ nemo::interpreter::define_function(def, env.clone()); }
conditional_block
main.rs
extern crate nemo; #[macro_use] extern crate clap; extern crate bounded_spsc_queue as queue; use std::io::{stdin, stdout, Write}; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::io; use std::io::prelude::*; use std::fs::File; use std::thread; use clap::{Arg, App}; fn
() { let matches = App::new("nemo") .version(crate_version!()) .author("Matthew S. <stanleybookowl@gmail.com>") .about("The nemo interpreter") .arg(Arg::with_name("INPUT") .help("Sets th...
main
identifier_name
memory.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 rustc_serialize::json; use std::net::TcpStream; use actor::{Actor, ActorRegistry, ActorMessageStatus}; #[der...
{ jsObjectSize: u64, jsStringSize: u64, jsOtherSize: u64, domSize: u64, styleSize: u64, otherSize: u64, totalSize: u64, jsMilliseconds: f64, nonJSMilliseconds: f64, } pub struct MemoryActor { pub name: String, } impl Actor for MemoryActor { fn name(&self) -> String { ...
TimelineMemoryReply
identifier_name
memory.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 rustc_serialize::json; use std::net::TcpStream; use actor::{Actor, ActorRegistry, ActorMessageStatus}; #[der...
totalSize: u64, jsMilliseconds: f64, nonJSMilliseconds: f64, } pub struct MemoryActor { pub name: String, } impl Actor for MemoryActor { fn name(&self) -> String { self.name.clone() } fn handle_message(&self, _registry: &ActorRegistry, _...
jsStringSize: u64, jsOtherSize: u64, domSize: u64, styleSize: u64, otherSize: u64,
random_line_split
utils.rs
use cgmath::*; use core::{self, Event, Handle, DXCore, DumpOnError}; use dxsafe::*; use dxsafe::structwrappers::*; use std::borrow::Cow; use std::ffi::OsString; use std::mem; use std::os::windows::ffi::OsStringExt; use std::os::windows::ffi::OsStrExt; use std::ptr; use std::slice; use user32::*; use winapi::*; use kern...
{ let mut ret = Vec::with_capacity(len); ret.set_len(len); // unsafe part ret }
identifier_body
utils.rs
use cgmath::*; use core::{self, Event, Handle, DXCore, DumpOnError}; use dxsafe::*; use dxsafe::structwrappers::*; use std::borrow::Cow; use std::ffi::OsString; use std::mem; use std::os::windows::ffi::OsStringExt; use std::os::windows::ffi::OsStrExt; use std::ptr; use std::slice; use user32::*; use winapi::*; use kern...
(core: &DXCore, fence: &D3D12Fence, fence_event: &Event) { match core::wait(&core.copy_queue, fence, fence_event) { Ok(_) => (), Err(hr) => { core.dump_info_queue_tagged("wait_for_copy_queue"); panic!("set_event_on_completion error: 0x{:x}", hr); } } } pub fn set...
wait_for_copy_queue
identifier_name
utils.rs
use cgmath::*; use core::{self, Event, Handle, DXCore, DumpOnError}; use dxsafe::*; use dxsafe::structwrappers::*; use std::borrow::Cow; use std::ffi::OsString; use std::mem; use std::os::windows::ffi::OsStringExt; use std::os::windows::ffi::OsStrExt; use std::ptr; use std::slice; use user32::*; use winapi::*; use kern...
try!(clist.close()); trace!("Command queue execute"); queue.execute_command_lists(&[&clist]); trace!("wait for copy queue"); try!(core::wait(queue, &fence, &fence_event).msg("upload texture wait error")); Ok(()) } pub fn create_depth_stencil(dev: &D3D12Device, w: u...
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); trace!("Command list Close");
random_line_split
tinylogger.rs
extern crate log; use log::{SetLoggerError, LogLevelFilter, LogMetadata, LogLevel, LogRecord}; pub struct TinyLogger; pub fn init(level: LogLevelFilter) -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(level); Box::new(TinyLogger) }) } impl log::Log for Tin...
fn log(&self, record: &LogRecord) { if self.enabled(record.metadata()) { let prompt = match record.level() { LogLevel::Trace => "[TACE]", LogLevel::Debug => "\u{001b}[37m[ DBG]\u{001b}[0m", LogLevel::Info => "\u{001b}[32m[INFO]\u{001b}[0m", ...
{ metadata.level() <= LogLevel::Debug }
identifier_body
tinylogger.rs
extern crate log; use log::{SetLoggerError, LogLevelFilter, LogMetadata, LogLevel, LogRecord}; pub struct TinyLogger; pub fn init(level: LogLevelFilter) -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(level); Box::new(TinyLogger) }) } impl log::Log for Tin...
(&self, metadata: &LogMetadata) -> bool { metadata.level() <= LogLevel::Debug } fn log(&self, record: &LogRecord) { if self.enabled(record.metadata()) { let prompt = match record.level() { LogLevel::Trace => "[TACE]", LogLevel::Debug => "\u{001b}[37m[...
enabled
identifier_name
tinylogger.rs
extern crate log; use log::{SetLoggerError, LogLevelFilter, LogMetadata, LogLevel, LogRecord}; pub struct TinyLogger; pub fn init(level: LogLevelFilter) -> Result<(), SetLoggerError> { log::set_logger(|max_log_level| { max_log_level.set(level); Box::new(TinyLogger) }) }
} fn log(&self, record: &LogRecord) { if self.enabled(record.metadata()) { let prompt = match record.level() { LogLevel::Trace => "[TACE]", LogLevel::Debug => "\u{001b}[37m[ DBG]\u{001b}[0m", LogLevel::Info => "\u{001b}[32m[INFO]\u{001b}[0m",...
impl log::Log for TinyLogger { fn enabled(&self, metadata: &LogMetadata) -> bool { metadata.level() <= LogLevel::Debug
random_line_split
check_menu_item.rs
// This file was generated by gir (5c017c9) from gir-files (71d73f0) // DO NOT EDIT use Actionable; use Bin; use Container; use MenuItem; use Widget; use ffi; use glib; use glib::object::Downcast; use glib::object::IsA; use glib::signal::connect; use glib::translate::*; use glib_ffi; use std::boxed::Box as Box_; use s...
fn toggled(&self) { unsafe { ffi::gtk_check_menu_item_toggled(self.to_glib_none().0); } } fn connect_toggled<F: Fn(&Self) +'static>(&self, f: F) -> u64 { unsafe { let f: Box_<Box_<Fn(&Self) +'static>> = Box_::new(Box_::new(f)); connect(self.to_g...
{ unsafe { ffi::gtk_check_menu_item_set_inconsistent(self.to_glib_none().0, setting.to_glib()); } }
identifier_body
check_menu_item.rs
// This file was generated by gir (5c017c9) from gir-files (71d73f0) // DO NOT EDIT use Actionable; use Bin; use Container; use MenuItem; use Widget; use ffi; use glib; use glib::object::Downcast;
use glib::object::IsA; use glib::signal::connect; use glib::translate::*; use glib_ffi; use std::boxed::Box as Box_; use std::mem::transmute; glib_wrapper! { pub struct CheckMenuItem(Object<ffi::GtkCheckMenuItem>): MenuItem, Bin, Container, Widget, Actionable; match fn { get_type => || ffi::gtk_check_...
random_line_split
check_menu_item.rs
// This file was generated by gir (5c017c9) from gir-files (71d73f0) // DO NOT EDIT use Actionable; use Bin; use Container; use MenuItem; use Widget; use ffi; use glib; use glib::object::Downcast; use glib::object::IsA; use glib::signal::connect; use glib::translate::*; use glib_ffi; use std::boxed::Box as Box_; use s...
(&self, is_active: bool) { unsafe { ffi::gtk_check_menu_item_set_active(self.to_glib_none().0, is_active.to_glib()); } } fn set_draw_as_radio(&self, draw_as_radio: bool) { unsafe { ffi::gtk_check_menu_item_set_draw_as_radio(self.to_glib_none().0, draw_as_radio.to...
set_active
identifier_name
uniq-self-in-mut-slot.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 ...
{ a: isize } trait Changer { fn change(mut self: Box<Self>) -> Box<Self>; } impl Changer for X { fn change(mut self: Box<X>) -> Box<X> { self.a = 55; self } } pub fn main() { let x: Box<_> = box X { a: 32 }; let new_x = x.change(); assert_eq!(new_x.a, 55); }
X
identifier_name
uniq-self-in-mut-slot.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 ...
fn change(mut self: Box<X>) -> Box<X> { self.a = 55; self } } pub fn main() { let x: Box<_> = box X { a: 32 }; let new_x = x.change(); assert_eq!(new_x.a, 55); }
trait Changer { fn change(mut self: Box<Self>) -> Box<Self>; } impl Changer for X {
random_line_split
uniq-self-in-mut-slot.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 x: Box<_> = box X { a: 32 }; let new_x = x.change(); assert_eq!(new_x.a, 55); }
identifier_body
font.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::font::{ FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel, }; use cr...
{ font_table: FontTable, pair_data_range: Range<usize>, px_per_font_unit: f64, } impl CachedKernTable { /// Search for a glyph pair in the kern table and return the corresponding value. fn binary_search(&self, first_glyph: GlyphId, second_glyph: GlyphId) -> Option<i16> { let pairs = &self....
CachedKernTable
identifier_name
font.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::font::{ FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel, }; use cr...
fn face_name(&self) -> Option<String> { Some(self.ctfont.face_name()) } fn style(&self) -> FontStyle { use style::values::generics::font::FontStyle::*; if self.ctfont.symbolic_traits().is_italic() { Italic } else { Normal } } fn bol...
{ Some(self.ctfont.family_name()) }
identifier_body
font.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::font::{ FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel, }; use cr...
use std::ops::Range; use std::sync::Arc; use std::{fmt, ptr}; use style::values::computed::font::{FontStretch, FontStyle, FontWeight}; const KERN_PAIR_LEN: usize = 6; pub struct FontTable { data: CFData, } // assumes 72 points per inch, and 96 px per inch fn px_to_pt(px: f64) -> f64 { px / 96. * 72. } // as...
use core_text::font_descriptor::kCTFontDefaultOrientation; use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; use servo_atoms::Atom;
random_line_split
font.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::font::{ FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel, }; use cr...
let pt_per_font_unit = self.ctfont.pt_size() as f64 / self.ctfont.units_per_em() as f64; result.px_per_font_unit = pt_to_px(pt_per_font_unit); } start = end; } } if result.pair_data_range.len() ...
{ debug!("Bad data in kern header. Disable fast path."); return None; }
conditional_block
data_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 base64; use mime::Mime; use servo_url::ServoUrl; use url::percent_encoding::percent_decode; use url::Position;...
// ";base64" must come at the end of the content type, per RFC 2397. // rust-http will fail to parse it because there's no =value part. let mut ct_str = parts[0]; let is_base64 = ct_str.ends_with(";base64"); if is_base64 { ct_str = &ct_str[..ct_str.len() - ";base64".len()]; } let ct_...
}
random_line_split
data_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 base64; use mime::Mime; use servo_url::ServoUrl; use url::percent_encoding::percent_decode; use url::Position;...
{ InvalidDataUri, NonBase64DataUri, } pub type DecodeData = (Mime, Vec<u8>); pub fn decode(url: &ServoUrl) -> Result<DecodeData, DecodeError> { assert_eq!(url.scheme(), "data"); // Split out content type and data. let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery] .spli...
DecodeError
identifier_name
monty_hall.rs
extern crate rand; use rand::Rng; use rand::distributions::{IndependentSample, Range}; struct SimulationResult { win: bool, switch: bool, } // Run a single simulation of the Monty Hall problem. fn simulate<R: Rng>(random_door: &Range<usize>, rng: &mut R) -> SimulationResult { let car = random_door.ind_sam...
let (mut switch_wins, mut switch_losses) = (0, 0); let (mut keep_wins, mut keep_losses) = (0, 0); println!("Running {} simulations...", num_simulations); for _ in 0..num_simulations { let result = simulate(&random_door, &mut rng); match (result.win, result.switch) { (true,...
let num_simulations = 100000; let mut rng = rand::thread_rng(); let random_door = Range::new(0, 3);
random_line_split
monty_hall.rs
extern crate rand; use rand::Rng; use rand::distributions::{IndependentSample, Range}; struct SimulationResult { win: bool, switch: bool, } // Run a single simulation of the Monty Hall problem. fn simulate<R: Rng>(random_door: &Range<usize>, rng: &mut R) -> SimulationResult
// Returns the door the game host opens given our choice and knowledge of // where the car is. The game host will never open the door with the car. fn game_host_open<R: Rng>(car: usize, choice: usize, rng: &mut R) -> usize { let choices = free_doors(&[car, choice]); rand::sample(rng, choices.into_iter(), 1)[0...
{ let car = random_door.ind_sample(rng); // This is our initial choice let mut choice = random_door.ind_sample(rng); // The game host opens a door let open = game_host_open(car, choice, rng); // Shall we switch? let switch = rng.gen(); if switch { choice = switch_door(choice, ...
identifier_body
monty_hall.rs
extern crate rand; use rand::Rng; use rand::distributions::{IndependentSample, Range}; struct
{ win: bool, switch: bool, } // Run a single simulation of the Monty Hall problem. fn simulate<R: Rng>(random_door: &Range<usize>, rng: &mut R) -> SimulationResult { let car = random_door.ind_sample(rng); // This is our initial choice let mut choice = random_door.ind_sample(rng); // The game...
SimulationResult
identifier_name
018.rs
// Copyright (C) 2014 Jorge Aparicio use std::cmp::max; use std::io::fs::File; use std::vec_ng::Vec; fn
() { let content = File::open(&Path::new("018.in")).read_to_str().unwrap(); let costs = content. lines(). map(|l| l.words().filter_map(from_str).collect::<Vec<uint>>()). fold(vec!(0), |a, b| { let n = b.len(); let mut c = Vec::with_capacity(n); ...
main
identifier_name
018.rs
// Copyright (C) 2014 Jorge Aparicio use std::cmp::max; use std::io::fs::File; use std::vec_ng::Vec; fn main()
c }); println!("{}", *costs.iter().max().unwrap()); }
{ let content = File::open(&Path::new("018.in")).read_to_str().unwrap(); let costs = content. lines(). map(|l| l.words().filter_map(from_str).collect::<Vec<uint>>()). fold(vec!(0), |a, b| { let n = b.len(); let mut c = Vec::with_capacity(n); ...
identifier_body
018.rs
// Copyright (C) 2014 Jorge Aparicio use std::cmp::max; use std::io::fs::File; use std::vec_ng::Vec; fn main() { let content = File::open(&Path::new("018.in")).read_to_str().unwrap(); let costs = content. lines(). map(|l| l.words().filter_map(from_str).collect::<Vec<uint>>()). ...
c.push(b.get(i) + *a.get(i)); } else if i == n - 1 { c.push(b.get(i) + *a.get(i - 1)); } else { c.push(b.get(i) + *max(a.get(i - 1), a.get(i))); } } c }); println!("{}", *cos...
let n = b.len(); let mut c = Vec::with_capacity(n); for i in range(0, n) { if i == 0 {
random_line_split
segment_merge_iterator.rs
use super::Segment; pub struct SegmentMergeIterator<I> { current: Option<Segment>, inner: I, } impl<I> SegmentMergeIterator<I> { pub fn new(inner: I) -> Self { SegmentMergeIterator { inner, current: None, } } } impl<I> Iterator for SegmentMergeIterator<I> where...
(&mut self) -> Option<Self::Item> { // Always work on an segment. if self.current.is_none() { self.current = self.inner.next(); self.current?; } // Keep growing our current segment until we find something else. loop { match self.inner.next() {...
next
identifier_name
segment_merge_iterator.rs
use super::Segment; pub struct SegmentMergeIterator<I> { current: Option<Segment>, inner: I, } impl<I> SegmentMergeIterator<I> { pub fn new(inner: I) -> Self { SegmentMergeIterator { inner, current: None, } } } impl<I> Iterator for SegmentMergeIterator<I> where...
Some(next) => { if next.span_id == self.current.unwrap().span_id { let current = self.current.as_mut().unwrap(); current.end = next.end; current.width += next.width; } else { ...
None => return self.current.take(),
random_line_split
segment_merge_iterator.rs
use super::Segment; pub struct SegmentMergeIterator<I> { current: Option<Segment>, inner: I, } impl<I> SegmentMergeIterator<I> { pub fn new(inner: I) -> Self { SegmentMergeIterator { inner, current: None, } } } impl<I> Iterator for SegmentMergeIterator<I> where...
} } } } }
{ let current = self.current.take(); self.current = Some(next); return current; }
conditional_block
mod.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/. */ //! The code to expose the DOM to JavaScript through IDL bindings. //! //! Exposing a DOM object to JavaScript //!...
//! Rust reflections of WebIDL types //! -------------------------------- //! //! The exact Rust representation for WebIDL types can depend on the precise //! way that they're being used (e.g., return values and arguments might have //! different representations). //! //! Optional arguments which do not have a default ...
//!
random_line_split
format.rs
/// Formatting macro for constructing `Ident`s. /// /// <br> /// /// # Syntax /// /// Syntax is copied from the [`format!`] macro, supporting both positional and /// named arguments. /// /// Only a limited set of formatting traits are supported. The current mapping /// of format types to traits is: /// /// * `{}` ⇒ [`I...
}; } #[macro_export] #[doc(hidden)] macro_rules! format_ident_impl { // Final state ([$span:expr, $($fmt:tt)*]) => { $crate::__private::mk_ident(&format!($($fmt)*), $span) }; // Span argument ([$old:expr, $($fmt:tt)*] span = $span:expr) => { $crate::format_ident_impl!([$old, $(...
($fmt:expr, $($rest:tt)*) => { $crate::format_ident_impl!([ ::std::option::Option::None, $fmt ] $($rest)*)
random_line_split
element.rs
use event; use text; use modifier; /// A stream representing a single element. #[derive(Debug)] pub struct SingleElement<S> { state: modifier::State<SingleElementState<S>>, } impl<S> SingleElement<S> { pub(crate) fn new(stream: S, event: event::Event) -> SingleElement<S> { SingleElement { ...
<S> { Start { event: event::Event, stream: S, }, EmitUntilClose { tag: text::Identifier, stream: S, level: usize, }, }
SingleElementState
identifier_name
element.rs
use event; use text; use modifier; /// A stream representing a single element. #[derive(Debug)] pub struct SingleElement<S> { state: modifier::State<SingleElementState<S>>, } impl<S> SingleElement<S> { pub(crate) fn new(stream: S, event: event::Event) -> SingleElement<S> { SingleElement { ...
SingleElementState::EmitUntilClose { tag, mut stream, level } => { let event = match stream.next_event()? { Some(event) => event, None => return Ok(None), }; if event.is_opening_tag_for(&tag) { Ok(Som...
random_line_split
element.rs
use event; use text; use modifier; /// A stream representing a single element. #[derive(Debug)] pub struct SingleElement<S> { state: modifier::State<SingleElementState<S>>, } impl<S> SingleElement<S> { pub(crate) fn new(stream: S, event: event::Event) -> SingleElement<S> { SingleElement { ...
tag, stream, level: level + 1, })))) } else if event.is_closing_tag_for(&tag) { if level == 0 { Ok(Some((event, None))) } else { ...
{ self.state.step(|state| match state { SingleElementState::Start { event, stream } => match event { event::Event(event::EventKind::OpeningTag { tag, attributes }) => Ok(Some(( event::open(tag.clone(), attributes), Some(SingleElementState::Emit...
identifier_body
ignores.rs
use maplit::hashset; use once_cell::sync::Lazy; use std::collections::HashSet; /// A list of builtin Python functions to ignore when generating relations of type `Relation::Use`. /// /// This list was generated using /// print(",\n".join([f"\"{symbol}\"" for symbol in dir(__builtins__)])) /// inside Python 3.8.10 (...
"FutureWarning", "GeneratorExit", "IOError", "ImportError", "ImportWarning", "IndentationError", "IndexError", "InterruptedError", "IsADirectoryError", "KeyError", "KeyboardInterrupt", "LookupError", "MemoryError", ...
"False", "FileExistsError", "FileNotFoundError", "FloatingPointError",
random_line_split
udp.rs
use {io, sys, Evented, Interest, IpAddr, PollOpt, Selector, Token}; use buf::{Buf, MutBuf}; use std::net::SocketAddr; #[derive(Debug)] pub struct UdpSocket { sys: sys::UdpSocket, } impl UdpSocket { /// Returns a new, unbound, non-blocking, IPv4 UDP socket pub fn v4() -> io::Result<UdpSocket> { sys...
(&self, multi: &IpAddr) -> io::Result<()> { self.sys.leave_multicast(multi) } pub fn set_multicast_time_to_live(&self, ttl: i32) -> io::Result<()> { self.sys.set_multicast_time_to_live(ttl) } } impl Evented for UdpSocket { fn register(&self, selector: &mut Selector, token: Token, inter...
leave_multicast
identifier_name
udp.rs
use {io, sys, Evented, Interest, IpAddr, PollOpt, Selector, Token}; use buf::{Buf, MutBuf}; use std::net::SocketAddr; #[derive(Debug)] pub struct UdpSocket { sys: sys::UdpSocket, } impl UdpSocket { /// Returns a new, unbound, non-blocking, IPv4 UDP socket pub fn v4() -> io::Result<UdpSocket> { sys...
} impl From<sys::UdpSocket> for UdpSocket { fn from(sys: sys::UdpSocket) -> UdpSocket { UdpSocket { sys: sys } } } /* * * ===== UNIX ext ===== * */ #[cfg(unix)] use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; #[cfg(unix)] impl AsRawFd for UdpSocket { fn as_raw_fd(&self) -> RawFd { ...
} fn deregister(&self, selector: &mut Selector) -> io::Result<()> { self.sys.deregister(selector) }
random_line_split
space-age.rs
use space_age::*; fn assert_in_delta(expected: f64, actual: f64) { let diff: f64 = (expected - actual).abs(); let delta: f64 = 0.01; if diff > delta { panic!( "Your result of {} should be within {} of the expected result {}", actual, delta, expected ) }
fn earth_age() { let duration = Duration::from(1_000_000_000); assert_in_delta(31.69, Earth::years_during(&duration)); } #[test] #[ignore] fn mercury_age() { let duration = Duration::from(2_134_835_688); assert_in_delta(280.88, Mercury::years_during(&duration)); } #[test] #[ignore] fn venus_age() { ...
} #[test]
random_line_split
space-age.rs
use space_age::*; fn assert_in_delta(expected: f64, actual: f64) { let diff: f64 = (expected - actual).abs(); let delta: f64 = 0.01; if diff > delta
} #[test] fn earth_age() { let duration = Duration::from(1_000_000_000); assert_in_delta(31.69, Earth::years_during(&duration)); } #[test] #[ignore] fn mercury_age() { let duration = Duration::from(2_134_835_688); assert_in_delta(280.88, Mercury::years_during(&duration)); } #[test] #[ignore] fn venu...
{ panic!( "Your result of {} should be within {} of the expected result {}", actual, delta, expected ) }
conditional_block
space-age.rs
use space_age::*; fn assert_in_delta(expected: f64, actual: f64) { let diff: f64 = (expected - actual).abs(); let delta: f64 = 0.01; if diff > delta { panic!( "Your result of {} should be within {} of the expected result {}", actual, delta, expected ) } } #[test...
#[test] #[ignore] fn mars_age() { let duration = Duration::from(2_129_871_239); assert_in_delta(35.88, Mars::years_during(&duration)); } #[test] #[ignore] fn jupiter_age() { let duration = Duration::from(901_876_382); assert_in_delta(2.41, Jupiter::years_during(&duration)); } #[test] #[ignore] fn sa...
{ let duration = Duration::from(189_839_836); assert_in_delta(9.78, Venus::years_during(&duration)); }
identifier_body
space-age.rs
use space_age::*; fn assert_in_delta(expected: f64, actual: f64) { let diff: f64 = (expected - actual).abs(); let delta: f64 = 0.01; if diff > delta { panic!( "Your result of {} should be within {} of the expected result {}", actual, delta, expected ) } } #[test...
() { let duration = Duration::from(2_129_871_239); assert_in_delta(35.88, Mars::years_during(&duration)); } #[test] #[ignore] fn jupiter_age() { let duration = Duration::from(901_876_382); assert_in_delta(2.41, Jupiter::years_during(&duration)); } #[test] #[ignore] fn saturn_age() { let duration =...
mars_age
identifier_name
main.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Benchmark testing // // Test serialization and deserialzation of a MicrovmState for a default VMM: // - 1 VCPU // - 128 MB memory size // - no devices use criterion::{black_box, criterion_group, c...
mem_file_path: memory_file.as_path().to_path_buf(), version: None, }; { let mut locked_vmm = vmm.lock().unwrap(); persist::create_snapshot(&mut locked_vmm, &snapshot_params, VERSION_MAP.clone()).unwrap(); } vmm.lock().unwrap().stop(FC_EXIT_CODE_OK); // Deserialize ...
{ let snapshot_file = TempFile::new().unwrap(); let memory_file = TempFile::new().unwrap(); let (vmm, _) = create_vmm(Some(NOISY_KERNEL_IMAGE), is_diff); // Be sure that the microVM is running. thread::sleep(Duration::from_millis(200)); // Pause microVM. vmm.lock().unwrap().pause_vm().unw...
identifier_body
main.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Benchmark testing // // Test serialization and deserialzation of a MicrovmState for a default VMM: // - 1 VCPU // - 128 MB memory size // - no devices use criterion::{black_box, criterion_group, c...
} #[inline] pub fn bench_create_snapshot<W: std::io::Write>( mut snapshot_writer: &mut W, vm: VersionMap, crc: bool, state: &mut MicrovmState, ) { let mut snapshot = Snapshot::new(vm.clone(), vm.latest_version()); if crc { snapshot.save(&mut snapshot_writer, state).unwrap(); } els...
{ Snapshot::unchecked_load::<&[u8], MicrovmState>(&mut snapshot_reader, vm).unwrap(); }
conditional_block
main.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Benchmark testing // // Test serialization and deserialzation of a MicrovmState for a default VMM: // - 1 VCPU // - 128 MB memory size // - no devices use criterion::{black_box, criterion_group, c...
(c: &mut Criterion) { let version_map = VERSION_MAP.clone(); // Create the microvm state let mut state = create_microvm_state(false); // Setup benchmarking with CRC let mut snapshot_state_with_crc = vec![0u8; 1024 * 1024 * 128]; let mut slice = &mut snapshot_state_with_crc.as_mut_slice(); ...
criterion_benchmark
identifier_name
main.rs
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Benchmark testing // // Test serialization and deserialzation of a MicrovmState for a default VMM: // - 1 VCPU // - 128 MB memory size // - no devices use criterion::{black_box, criterion_group, c...
snapshot_len, VERSION_MAP.clone(), ) .unwrap(); microvm_state } pub fn criterion_benchmark(c: &mut Criterion) { let version_map = VERSION_MAP.clone(); // Create the microvm state let mut state = create_microvm_state(false); // Setup benchmarking with CRC let mut snapsh...
random_line_split
isogram.rs
extern crate isogram; use isogram::check; #[test] fn
() { assert_eq!(check(""), true, "An empty string should be an isogram.") } #[test] fn only_lower_case_characters() { assert_eq!(check("isogram"), true, "\"isogram\" should be an isogram.") } #[test] fn one_duplicated_character() { assert_eq!( check("eleven"), false, "\"eleven\" ha...
empty_string
identifier_name
isogram.rs
extern crate isogram; use isogram::check; #[test] fn empty_string() { assert_eq!(check(""), true, "An empty string should be an isogram.") } #[test] fn only_lower_case_characters() { assert_eq!(check("isogram"), true, "\"isogram\" should be an isogram.") } #[test] fn one_duplicated_character() { assert_...
#[test] fn made_up_name_that_is_an_isogram() { assert_eq!( check("Emily Jung Schwartzkopf"), true, "\"Emily Jung Schwartzkopf\" should be an isogram." ) } #[test] fn duplicated_character_in_the_middle() { assert_eq!( check("accentor"), false, "\"accentor\" ...
{ assert_eq!( check("six-year-old"), true, "\"six-year-old\" should be an isogram." ) }
identifier_body
isogram.rs
extern crate isogram; use isogram::check; #[test] fn empty_string() { assert_eq!(check(""), true, "An empty string should be an isogram.") } #[test] fn only_lower_case_characters() { assert_eq!(check("isogram"), true, "\"isogram\" should be an isogram.") } #[test] fn one_duplicated_character() { assert_...
#[test] fn longest_reported_english_isogram() { assert_eq!( check("subdermatoglyphic"), true, "\"subdermatoglyphic\" should be an isogram." ) } #[test] fn one_duplicated_character_mixed_case() { assert_eq!( check("Alphabet"), false, "\"Alphabet\" has more th...
}
random_line_split
str.rs
fn
() { // (all the type annotations are superfluous) // A reference to a string allocated in read only memory let pangram: &'static str = "the quick brown fox jumps over the lazy dog"; println!("Pangram: {}", pangram); // Iterate over words in reverse, no new string is allocated println!("Words i...
main
identifier_name
str.rs
fn main()
// Insert a char at the end of string string.push(c); // Insert a string at the end of string string.push_str(", "); } // The trimmed string is a slice to the original string, hence no new // allocation is performed let chars_to_trim: &[char] = [' ', ',']; let trimme...
{ // (all the type annotations are superfluous) // A reference to a string allocated in read only memory let pangram: &'static str = "the quick brown fox jumps over the lazy dog"; println!("Pangram: {}", pangram); // Iterate over words in reverse, no new string is allocated println!("Words in r...
identifier_body
str.rs
fn main() { // (all the type annotations are superfluous) // A reference to a string allocated in read only memory let pangram: &'static str = "the quick brown fox jumps over the lazy dog"; println!("Pangram: {}", pangram); // Iterate over words in reverse, no new string is allocated println!("...
chars.sort(); chars.dedup(); // Create an empty and growable `String` let mut string = String::new(); for c in chars.into_iter() { // Insert a char at the end of string string.push(c); // Insert a string at the end of string string.push_str(", "); } // The t...
// Copy chars into a vector, sort and remove duplicates let mut chars: Vec<char> = pangram.chars().collect();
random_line_split
player.rs
// MIT License // // Copyright (c) 2017 Franziska Becker, René Warking // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
} /// Reverse a capture pub fn reverse_capture(&mut self, name: String, pos: Position) { let mut found = false; if let Some(mut v) = self.figures.get_mut(&name) { v.push(pos); found = true; } if!found { self.figures.insert(name, vec![pos]...
self.figures.remove(&name); }
conditional_block
player.rs
// MIT License // // Copyright (c) 2017 Franziska Becker, René Warking // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
pub fn get_ai_move(&self, board: &Board, other: &Player) -> (Position, Position) { return super::ai::get_move(board, self, other); } /// Move a figure from 'before' to 'after' pub fn move_figure(&mut self, before: Position, after: Position) { for mut v in self.figures.values_mut() { ...
random_line_split
player.rs
// MIT License // // Copyright (c) 2017 Franziska Becker, René Warking // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
/// Return the player's king which should always be there because one /// cannot actually 'capture' a king pub fn king(&self) -> Position { self.figures.get("king").unwrap()[0] } /// Returns a vector of possible moves for all figures of the player pub fn get_possible_moves(&mut self, b...
self.capture("pawn".to_string(), pos); let mut found = false; if let Some(mut positions) = self.figures.get_mut("queen") { positions.push(pos); found = true; } if !found { self.figures.insert("queen".to_string(), vec![pos]); } }
identifier_body
player.rs
// MIT License // // Copyright (c) 2017 Franziska Becker, René Warking // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to...
&self) -> Position { self.figures.get("king").unwrap()[0] } /// Returns a vector of possible moves for all figures of the player pub fn get_possible_moves(&mut self, board: &mut Board, opponent: &mut Player) -> Vec<(Position, Position)> { let mut moves = Vec::new(); for v in self.f...
ing(
identifier_name
edit.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
else { Ok(()) }) }
{ Err(Error::from(EM::ExternalProcessError)) }
conditional_block
edit.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
fn edit_header(&mut self, rt: &Runtime) -> Result<()>; fn edit_header_and_content(&mut self, rt: &Runtime) -> Result<()>; } impl Edit for String { fn edit_content(&mut self, rt: &Runtime) -> Result<()> { edit_in_tmpfile(rt, self).map(|_| ()) } } impl Edit for Entry { fn edit...
fn edit_content(&mut self, rt: &Runtime) -> Result<()>; } pub trait EditHeader : Edit {
random_line_split
edit.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
(&mut self, rt: &Runtime) -> Result<()> { let mut header = ::toml::ser::to_string_pretty(self.get_header())?; edit_in_tmpfile(rt, &mut header)?; let header = ::toml::de::from_str(&header)?; *self.get_header_mut() = header; Ok(()) } fn edit_header_and_content(&mut sel...
edit_header
identifier_name
edit.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
} impl EditHeader for Entry { fn edit_header(&mut self, rt: &Runtime) -> Result<()> { let mut header = ::toml::ser::to_string_pretty(self.get_header())?; edit_in_tmpfile(rt, &mut header)?; let header = ::toml::de::from_str(&header)?; *self.get_header_mut() = header; O...
{ edit_in_tmpfile(rt, self.get_content_mut()) .map(|_| ()) }
identifier_body
restoration_status.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Statuses for restorations. #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum RestorationStatus { /// No restoration. Inactive, /// Ongoing restoration. Ongoing { /// Total number of state chunks. state_chunks: u32, /// Total number of block chunks. block_chunks: u32, /// Number of state chunks co...
//! Restoration status type definition
random_line_split
restoration_status.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
{ /// No restoration. Inactive, /// Ongoing restoration. Ongoing { /// Total number of state chunks. state_chunks: u32, /// Total number of block chunks. block_chunks: u32, /// Number of state chunks completed. state_chunks_done: u32, /// Number of block chunks completed. block_chunks_done: u32, }...
RestorationStatus
identifier_name
emulator.rs
extern crate dcpu16; extern crate getopts; mod cli; use std::vec::Vec; use std::path::Path; use std::{env, thread, time}; use dcpu16::dcpu; use dcpu16::disassembler; //use dcpu16::bin::cli; use getopts::Options; use std::process::exit; use dcpu16::devices::clock_generic::DeviceClockGeneric; const FPS: usize = 30; ...
, Err(why) => { println!("Could load file {}: {}", path.display(), why); exit(1); }, } // Connect hardware //cpu.devices.push(Box::new(dcpu::HWMonitorLEM1802{connected: false, ram_location: 0})); /* let mut floppy = Box::new(dcpu::HWFloppyM35FD::new()); f...
{}
conditional_block
emulator.rs
extern crate dcpu16; extern crate getopts; mod cli; use std::vec::Vec; use std::path::Path; use std::{env, thread, time}; use dcpu16::dcpu; use dcpu16::disassembler; //use dcpu16::bin::cli; use getopts::Options; use std::process::exit; use dcpu16::devices::clock_generic::DeviceClockGeneric; const FPS: usize = 30; ...
() { let mut opts = Options::new(); let args: Vec<String> = env::args().collect(); let program = args[0].clone(); opts.optflag("p", "print", "print CPU info each tick"); opts.optflag("v", "version", "print version"); opts.optflag("h", "help", "print this help menu"); let matches = match opt...
main
identifier_name
emulator.rs
extern crate dcpu16; extern crate getopts; mod cli; use std::vec::Vec; use std::path::Path; use std::{env, thread, time}; use dcpu16::dcpu; use dcpu16::disassembler; //use dcpu16::bin::cli; use getopts::Options; use std::process::exit; use dcpu16::devices::clock_generic::DeviceClockGeneric; const FPS: usize = 30; ...
opts.optflag("h", "help", "print this help menu"); let matches = match opts.parse(&args[1..]) { Ok(m) => { m }, Err(why) => { println!("{}", why); exit(1); }, }; if matches.opt_present("h") { cli::print_usage(&program, "FILE", opts, &["-p output.b...
random_line_split
emulator.rs
extern crate dcpu16; extern crate getopts; mod cli; use std::vec::Vec; use std::path::Path; use std::{env, thread, time}; use dcpu16::dcpu; use dcpu16::disassembler; //use dcpu16::bin::cli; use getopts::Options; use std::process::exit; use dcpu16::devices::clock_generic::DeviceClockGeneric; const FPS: usize = 30; ...
if matches.opt_present("v") { cli::print_version(&program); return; } if matches.free.len()!= 1 { println!("Please input file"); return; } let print = matches.opt_present("p"); let ref filename = matches.free[0]; let mut cpu = dcpu::DCPU::new(); let pa...
{ let mut opts = Options::new(); let args: Vec<String> = env::args().collect(); let program = args[0].clone(); opts.optflag("p", "print", "print CPU info each tick"); opts.optflag("v", "version", "print version"); opts.optflag("h", "help", "print this help menu"); let matches = match opts.p...
identifier_body
canvasrenderingcontext2d.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::CanvasRenderingContext2DBinding; use dom::bindings::codegen::Bindings::Canva...
} #[unsafe_destructor] impl Drop for CanvasRenderingContext2D { fn drop(&mut self) { self.renderer.send(Close); } }
{ let rect = Rect(Point2D(x as f32, y as f32), Size2D(width as f32, height as f32)); self.renderer.send(StrokeRect(rect)); }
identifier_body
canvasrenderingcontext2d.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::CanvasRenderingContext2DBinding; use dom::bindings::codegen::Bindings::Canva...
(self) -> Temporary<HTMLCanvasElement> { Temporary::new(self.canvas) } fn FillRect(self, x: f64, y: f64, width: f64, height: f64) { let rect = Rect(Point2D(x as f32, y as f32), Size2D(width as f32, height as f32)); self.renderer.send(FillRect(rect)); } fn ClearRect(self, x: f64...
Canvas
identifier_name
canvasrenderingcontext2d.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::CanvasRenderingContext2DBinding; use dom::bindings::codegen::Bindings::Canva...
#[dom_struct] pub struct CanvasRenderingContext2D { reflector_: Reflector, global: GlobalField, renderer: Sender<CanvasMsg>, canvas: JS<HTMLCanvasElement>, } impl CanvasRenderingContext2D { fn new_inherited(global: GlobalRef, canvas: JSRef<HTMLCanvasElement>, size: Size2D<i32>) -> CanvasRenderingC...
use geom::size::Size2D; use canvas::canvas_paint_task::{CanvasMsg, CanvasPaintTask}; use canvas::canvas_paint_task::CanvasMsg::{ClearRect, Close, FillRect, Recreate, StrokeRect};
random_line_split
mozmap.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/. */ //! The `MozMap` (open-ended dictionary) type. use dom::bindings::conversions::jsid_to_string; use dom::bindings:...
} impl<T, C> FromJSValConvertible for MozMap<T> where T: FromJSValConvertible<Config=C>, C: Clone, { type Config = C; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C) -> Result<ConversionResult<Self>, ()> { if!value.is_object() { ...
{ &self.map }
identifier_body
mozmap.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/. */ //! The `MozMap` (open-ended dictionary) type. use dom::bindings::conversions::jsid_to_string; use dom::bindings:...
(&self) -> &HashMap<DOMString, T> { &self.map } } impl<T, C> FromJSValConvertible for MozMap<T> where T: FromJSValConvertible<Config=C>, C: Clone, { type Config = C; unsafe fn from_jsval(cx: *mut JSContext, value: HandleValue, config: C) -> Result<ConversionRe...
deref
identifier_name
mozmap.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/. */ //! The `MozMap` (open-ended dictionary) type. use dom::bindings::conversions::jsid_to_string;
use js::jsapi::GetPropertyKeys; use js::jsapi::HandleValue; use js::jsapi::JSContext; use js::jsapi::JSITER_OWNONLY; use js::jsapi::JSPROP_ENUMERATE; use js::jsapi::JS_DefineUCProperty2; use js::jsapi::JS_GetPropertyById; use js::jsapi::JS_NewPlainObject; use js::jsapi::MutableHandleValue; use js::jsval::ObjectValue; u...
use dom::bindings::str::DOMString; use js::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionResult};
random_line_split
state.rs
use std::{ cell::RefCell, rc::Rc, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, }; use smithay::{ reexports::{ calloop::{generic::Generic, Interest, LoopHandle, Mode, PostAction}, wayland_server::{protocol::wl_surface::WlSurface, Display}, }, utils::...
// Init the basic compositor globals init_shm_global(&mut (*display).borrow_mut(), vec![], log.clone()); let shell_handles = init_shell::<BackendData>(display.clone(), log.clone()); init_xdg_output_manager(&mut display.borrow_mut(), log.clone()); init_xdg_activation_global( ...
{ // init the wayland connection handle .insert_source( Generic::from_fd(display.borrow().get_poll_fd(), Interest::READ, Mode::Level), move |_, _, state: &mut AnvilState<BackendData>| { let display = state.display.clone(); ...
identifier_body
state.rs
use std::{ cell::RefCell, rc::Rc, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, }; use smithay::{ reexports::{ calloop::{generic::Generic, Interest, LoopHandle, Mode, PostAction}, wayland_server::{protocol::wl_surface::WlSurface, Display}, }, utils::...
<BackendData> { pub backend_data: BackendData, pub socket_name: Option<String>, pub running: Arc<AtomicBool>, pub display: Rc<RefCell<Display>>, pub handle: LoopHandle<'static, AnvilState<BackendData>>, pub window_map: Rc<RefCell<crate::window_map::WindowMap>>, pub output_map: Rc<RefCell<cra...
AnvilState
identifier_name
state.rs
use std::{ cell::RefCell, rc::Rc, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, }; use smithay::{ reexports::{ calloop::{generic::Generic, Interest, LoopHandle, Mode, PostAction}, wayland_server::{protocol::wl_surface::WlSurface, Display}, }, utils::...
if token_data.timestamp.elapsed().as_secs() < 10 { // Just grant the wish anvil_state.window_map.borrow_mut().bring_surface_to_top(&surface); } else { // Discard the request ...
XdgActivationEvent::RequestActivation { token, token_data, surface, } => {
random_line_split
prun.rs
#[doc = "Register `PRUN` reader"] pub struct R(crate::R<PRUN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PRUN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0
#[inline(always)] fn from(reader: crate::R<PRUN_SPEC>) -> Self { R(reader) } } #[doc = "Run Bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RB_A { #[doc = "0: IDLE"] VALUE1 = 0, #[doc = "1: Running"] VALUE2 = 1, } impl From<RB_A> for bool { #[inline(a...
} } impl From<crate::R<PRUN_SPEC>> for R {
random_line_split
prun.rs
#[doc = "Register `PRUN` reader"] pub struct R(crate::R<PRUN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PRUN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PRUN_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PRUN_SP...
} impl R { #[doc = "Bit 0 - Run Bit"] #[inline(always)] pub fn rb(&self) -> RB_R { RB_R::new((self.bits & 0x01)!= 0) } } #[doc = "Service Request Processing Run Bit Status\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api)....
{ &self.0 }
identifier_body
prun.rs
#[doc = "Register `PRUN` reader"] pub struct R(crate::R<PRUN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PRUN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PRUN_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PRUN_SP...
; impl crate::RegisterSpec for PRUN_SPEC { type Ux = u32; } #[doc = "`read()` method returns [prun::R](R) reader structure"] impl crate::Readable for PRUN_SPEC { type Reader = R; } #[doc = "`reset()` method sets PRUN to value 0"] impl crate::Resettable for PRUN_SPEC { #[inline(always)] fn reset_value() ...
PRUN_SPEC
identifier_name
i32.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 ...
impl BitCount for i32 { /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. #[inline] fn population_count(&self) -> i32 { unsafe { intrinsics::ctpop32(*self) } } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline] fn leading_zeros(&self) -> i32 { uns...
int_module!(i32, 32)
random_line_split
i32.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 ...
} } }
{ Some(x) }
conditional_block
i32.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> i32 { unsafe { intrinsics::ctpop32(*self) } } /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. #[inline] fn leading_zeros(&self) -> i32 { unsafe { intrinsics::ctlz32(*self) } } /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. #[inline] fn...
population_count
identifier_name
i32.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 ...
} impl CheckedSub for i32 { #[inline] fn checked_sub(&self, v: &i32) -> Option<i32> { unsafe { let (x, y) = intrinsics::i32_sub_with_overflow(*self, *v); if y { None } else { Some(x) } } } } impl CheckedMul for i32 { #[inline] fn checked_mul(&self, v: &i32)...
{ unsafe { let (x, y) = intrinsics::i32_add_with_overflow(*self, *v); if y { None } else { Some(x) } } }
identifier_body
create-contact.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain;
struct Opt { /// The name of the contact list. #[structopt(short, long)] contact_list: String, /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The email address of the contact to add to the contact list. #[structopt(short, long)] email_address: String, ...
use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)]
random_line_split
create-contact.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The name of the co...
let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); add_contact(&client, &contact_list, &email_address).await }
{ println!("SES client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("Contact list: {}", &contact_list); println!("Email address: {}", &email_address); printl...
conditional_block
create-contact.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The name of the co...
// snippet-end:[ses.rust.create-contact] /// Adds a contact to the contact list in the Region. /// # Arguments /// /// * `-c CONTACT-LIST` - The name of the contact list. /// * `-e EMAIL-ADDRESS` - The email address of the contact to add to the contact list. /// * `[-r REGION]` - The Region in which the client is cre...
{ client .create_contact() .contact_list_name(list) .email_address(email) .send() .await?; println!("Created contact"); Ok(()) }
identifier_body
create-contact.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_sesv2::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct
{ /// The name of the contact list. #[structopt(short, long)] contact_list: String, /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// The email address of the contact to add to the contact list. #[structopt(short, long)] email_address: String, /// Whet...
Opt
identifier_name