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
builder.rs
use super::{op::*, Script}; use crate::{constants::MAX_SCRIPT_BYTE_SIZE, serializer::*}; type FnRef = (u8, u32); // ID, pointer #[derive(Clone, Debug, Default)] pub struct Builder { lookup_table: Vec<FnRef>, body: Vec<u8>, } impl Builder { pub fn new() -> Self { Self { lookup_table: V...
pub fn push(mut self, frame: OpFrame) -> Self { match frame { // Function definition OpFrame::OpDefine(_) => panic!("OpDefine cannot be pushed in a function"), // Events OpFrame::OpTransfer => self.byte_code.push(Operand::OpTransfer.into()), // Pu...
Self { id, byte_code } }
random_line_split
builder.rs
use super::{op::*, Script}; use crate::{constants::MAX_SCRIPT_BYTE_SIZE, serializer::*}; type FnRef = (u8, u32); // ID, pointer #[derive(Clone, Debug, Default)] pub struct Builder { lookup_table: Vec<FnRef>, body: Vec<u8>, } impl Builder { pub fn
() -> Self { Self { lookup_table: Vec::new(), body: Vec::new(), } } /// Returns the script on success, otherwise an error with the total script size that has exceeded the max script /// byte size. pub fn build(self) -> Result<Script, usize> { // 1 byte fo...
new
identifier_name
mod.rs
pub mod compare; pub mod sort; pub mod tool; pub use self::compare::*; pub use self::sort::*; use gossyp_base::*; use gossyp_base::basic::*; /// /// ToolSet containing the algorithm tools /// pub struct AlgorithmTools { } impl AlgorithmTools { pub fn new() -> AlgorithmTools { AlgorithmTools { } } } ...
fn create_tools(self, environment: &Environment) -> Vec<(String, Box<Tool>)> { (&self).create_tools(environment) } }
impl ToolSet for AlgorithmTools {
random_line_split
mod.rs
pub mod compare; pub mod sort; pub mod tool; pub use self::compare::*; pub use self::sort::*; use gossyp_base::*; use gossyp_base::basic::*; /// /// ToolSet containing the algorithm tools /// pub struct
{ } impl AlgorithmTools { pub fn new() -> AlgorithmTools { AlgorithmTools { } } } impl<'a> ToolSet for &'a AlgorithmTools { fn create_tools(self, _environment: &Environment) -> Vec<(String, Box<Tool>)> { vec![ (String::from(self::tool::COMPARE_VALUES), Box::new(CompareTool::n...
AlgorithmTools
identifier_name
mod.rs
pub mod compare; pub mod sort; pub mod tool; pub use self::compare::*; pub use self::sort::*; use gossyp_base::*; use gossyp_base::basic::*; /// /// ToolSet containing the algorithm tools /// pub struct AlgorithmTools { } impl AlgorithmTools { pub fn new() -> AlgorithmTools { AlgorithmTools { } } } ...
}
{ (&self).create_tools(environment) }
identifier_body
configpaths_06.rs
use libnewsboat::configpaths::ConfigPaths; use section_testing::{enable_sections, section}; use std::{env, fs, path}; use tempfile::TempDir; fn assert_paths_are_inside_dirs(config_dir: &path::Path, data_dir: &path::Path) { let paths = ConfigPaths::new(); assert!(paths.initialized()); assert_eq!(paths.confi...
assert_eq!(paths.cmdline_file(), data_dir.join("history.cmdline")); } enable_sections! { #[test] fn t_configpaths_returns_paths_to_newsboat_xdg_dirs_if_they_exist_and_dotdir_doesnt() { let tmp = TempDir::new().unwrap(); let config_dir = tmp.path().join(".config").join("newsboat"); fs::create_dir_all(&c...
random_line_split
configpaths_06.rs
use libnewsboat::configpaths::ConfigPaths; use section_testing::{enable_sections, section}; use std::{env, fs, path}; use tempfile::TempDir; fn
(config_dir: &path::Path, data_dir: &path::Path) { let paths = ConfigPaths::new(); assert!(paths.initialized()); assert_eq!(paths.config_file(), config_dir.join("config")); assert_eq!(paths.url_file(), config_dir.join("urls")); assert_eq!(paths.cache_file(), data_dir.join("cache.db")); assert_e...
assert_paths_are_inside_dirs
identifier_name
configpaths_06.rs
use libnewsboat::configpaths::ConfigPaths; use section_testing::{enable_sections, section}; use std::{env, fs, path}; use tempfile::TempDir; fn assert_paths_are_inside_dirs(config_dir: &path::Path, data_dir: &path::Path)
enable_sections! { #[test] fn t_configpaths_returns_paths_to_newsboat_xdg_dirs_if_they_exist_and_dotdir_doesnt() { let tmp = TempDir::new().unwrap(); let config_dir = tmp.path().join(".config").join("newsboat"); fs::create_dir_all(&config_dir).ok(); let data_dir = tmp.path().join(".local").join("share...
{ let paths = ConfigPaths::new(); assert!(paths.initialized()); assert_eq!(paths.config_file(), config_dir.join("config")); assert_eq!(paths.url_file(), config_dir.join("urls")); assert_eq!(paths.cache_file(), data_dir.join("cache.db")); assert_eq!(paths.lock_file(), data_dir.join("cache.db.loc...
identifier_body
self_user.rs
use crate::server::is_authenticated; use crate::server::model::guild::GuildModel; use crate::server::model::self_user::SelfUserModel; use crate::service::user_secret::UserSecretService; use crate::Config; use actix_web::{get, web, HttpResponse, Responder}; use typemap_rev::TypeMap; #[get("/@me")] pub async fn
( config: web::Data<Config>, services: web::Data<TypeMap>, req: web::HttpRequest, ) -> impl Responder { let user_id = if let Some(id) = is_authenticated(&config, &services, &req).await { id } else { return HttpResponse::Unauthorized().finish(); }; let user_secret_service = i...
get_self
identifier_name
self_user.rs
use crate::server::is_authenticated; use crate::server::model::guild::GuildModel; use crate::server::model::self_user::SelfUserModel; use crate::service::user_secret::UserSecretService; use crate::Config; use actix_web::{get, web, HttpResponse, Responder}; use typemap_rev::TypeMap; #[get("/@me")] pub async fn get_self...
id } else { return HttpResponse::Unauthorized().finish(); }; let user_secret_service = if let Some(service) = services.get::<UserSecretService>() { service } else { return HttpResponse::InternalServerError().finish(); }; let self_user_guilds: Vec<GuildModel> = m...
services: web::Data<TypeMap>, req: web::HttpRequest, ) -> impl Responder { let user_id = if let Some(id) = is_authenticated(&config, &services, &req).await {
random_line_split
self_user.rs
use crate::server::is_authenticated; use crate::server::model::guild::GuildModel; use crate::server::model::self_user::SelfUserModel; use crate::service::user_secret::UserSecretService; use crate::Config; use actix_web::{get, web, HttpResponse, Responder}; use typemap_rev::TypeMap; #[get("/@me")] pub async fn get_self...
else { return HttpResponse::Unauthorized().finish(); }; let user_secret_service = if let Some(service) = services.get::<UserSecretService>() { service } else { return HttpResponse::InternalServerError().finish(); }; let self_user_guilds: Vec<GuildModel> = match user_secret...
{ id }
conditional_block
self_user.rs
use crate::server::is_authenticated; use crate::server::model::guild::GuildModel; use crate::server::model::self_user::SelfUserModel; use crate::service::user_secret::UserSecretService; use crate::Config; use actix_web::{get, web, HttpResponse, Responder}; use typemap_rev::TypeMap; #[get("/@me")] pub async fn get_self...
id: guild.id.to_string(), name: guild.name.clone(), icon_url: guild.icon_url.clone(), }) .collect(), Err(_) => return HttpResponse::Unauthorized().finish(), }; let self_user = match user_secret_service.get_self_user(user_id).await {...
{ let user_id = if let Some(id) = is_authenticated(&config, &services, &req).await { id } else { return HttpResponse::Unauthorized().finish(); }; let user_secret_service = if let Some(service) = services.get::<UserSecretService>() { service } else { return HttpRespon...
identifier_body
playbin.rs
use ffi::*; use pipeline::Pipeline; use element::Element; use ::Transfer; use reference::Reference; use std::ops::{Deref, DerefMut}; unsafe impl Sync for PlayBin {} unsafe impl Send for PlayBin {} pub struct PlayBin{ playbin: Pipeline } impl PlayBin{ pub fn new(name: &str) -> Option<PlayBin>{ let p...
(&mut self, force_aspect_ratio: bool){ self.set("force-aspect-ratio", force_aspect_ratio as gboolean); } pub fn set_audio_stream_combiner(&mut self, audio_stream_combiner: &Element){ self.set("audio-stream-combiner", audio_stream_combiner); } pub fn set_video_stream_combiner(&mut self,...
set_force_aspect_ratio
identifier_name
playbin.rs
use ffi::*; use pipeline::Pipeline; use element::Element; use ::Transfer; use reference::Reference; use std::ops::{Deref, DerefMut}; unsafe impl Sync for PlayBin {} unsafe impl Send for PlayBin {} pub struct PlayBin{ playbin: Pipeline } impl PlayBin{ pub fn new(name: &str) -> Option<PlayBin>{ let p...
pub fn set_uri(&mut self, uri: &str){ self.set("uri", uri); } pub fn set_force_aspect_ratio(&mut self, force_aspect_ratio: bool){ self.set("force-aspect-ratio", force_aspect_ratio as gboolean); } pub fn set_audio_stream_combiner(&mut self, audio_stream_combiner: &Element){ ...
{ self.set("text-sink", textsink); }
identifier_body
playbin.rs
use ffi::*; use pipeline::Pipeline; use element::Element; use ::Transfer; use reference::Reference; use std::ops::{Deref, DerefMut}; unsafe impl Sync for PlayBin {} unsafe impl Send for PlayBin {} pub struct PlayBin{ playbin: Pipeline } impl PlayBin{ pub fn new(name: &str) -> Option<PlayBin>{ let p...
self.set("flags", flags); } } impl ::Transfer for PlayBin{ unsafe fn transfer(self) -> *mut GstElement{ self.playbin.transfer() } } impl Reference for PlayBin{ fn reference(&self) -> PlayBin{ PlayBin{ playbin: self.playbin.reference()} } } impl AsRef<Pipeline> for PlayBin{...
} pub fn set_flags(&mut self, flags: i32){
random_line_split
visitor.rs
use rustc::middle::{ty, def}; use rustc::middle::ty::MethodCall; use syntax::{ast, ast_util, ast_map}; use syntax::codemap::Span; use syntax::parse::token; use syntax::visit; use syntax::visit::Visitor; use std::fmt; use std::mem::replace; use std::collections::BTreeMap; fn type_is_unsafe_function(ty: ty::Ty) -> boo...
(&mut self, block: &'a ast::Block) { let (old_node_info, inserted) = match block.rules { ast::DefaultBlock => (None, false), ast::UnsafeBlock(source) => { let compiler = source == ast::CompilerGenerated; if self.node_info.is_none() || compiler { ...
visit_block
identifier_name
visitor.rs
use rustc::middle::{ty, def}; use rustc::middle::ty::MethodCall; use syntax::{ast, ast_util, ast_map}; use syntax::codemap::Span; use syntax::parse::token; use syntax::visit; use syntax::visit::Visitor; use std::fmt; use std::mem::replace; use std::collections::BTreeMap; fn type_is_unsafe_function(ty: ty::Ty) -> boo...
ast::ExprInlineAsm(..) => { self.info().asm.push(expr.span) } ast::ExprPath(..) => { match ty::resolve_expr(self.tcx, expr) { def::DefStatic(_, true) => { self.info().static_mut.p...
{ let base_type = ty::node_id_to_type(self.tcx, base.id); match base_type.sty { ty::ty_ptr(_) => { self.info().raw_deref.push(expr.span) } _ => {} } ...
conditional_block
visitor.rs
use rustc::middle::{ty, def}; use rustc::middle::ty::MethodCall; use syntax::{ast, ast_util, ast_map}; use syntax::codemap::Span; use syntax::parse::token; use syntax::visit; use syntax::visit::Visitor; use std::fmt; use std::mem::replace; use std::collections::BTreeMap; fn type_is_unsafe_function(ty: ty::Ty) -> boo...
match base_type.sty { ty::ty_ptr(_) => { self.info().raw_deref.push(expr.span) } _ => {} } } ast::ExprInlineAsm(..) => { self.in...
} ast::ExprUnary(ast::UnDeref, ref base) => { let base_type = ty::node_id_to_type(self.tcx, base.id);
random_line_split
rfc3596.rs
//! Record data from [RFC 3596]. //! //! This RFC defines the Aaaa record type. //! //! [RFC 3596]: https://tools.ietf.org/html/rfc3596 use std::fmt; use std::net::Ipv6Addr; use std::str::FromStr; use ::bits::{Composable, Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordDa...
(addr: Ipv6Addr) -> Aaaa { Aaaa { addr: addr } } pub fn addr(&self) -> Ipv6Addr { self.addr } pub fn set_addr(&mut self, addr: Ipv6Addr) { self.addr = addr } fn parse_always(parser: &mut Parser) -> ParseResult<Self> { Ok(Aaaa::new(Ipv6Addr::new(try!(parser.parse_u16()), ...
new
identifier_name
rfc3596.rs
//! Record data from [RFC 3596]. //! //! This RFC defines the Aaaa record type. //! //! [RFC 3596]: https://tools.ietf.org/html/rfc3596 use std::fmt; use std::net::Ipv6Addr; use std::str::FromStr; use ::bits::{Composable, Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordDa...
} impl RecordData for Aaaa { fn rtype(&self) -> Rtype { Rtype::Aaaa } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { for i in &self.addr.segments() { try!(i.compose(target.as_mut())); } Ok(()) } } impl<'a>...
scanner.scan_str_phrase(|slice| { let addr = try!(Ipv6Addr::from_str(slice)); Ok(Aaaa::new(addr)) }) }
random_line_split
rfc3596.rs
//! Record data from [RFC 3596]. //! //! This RFC defines the Aaaa record type. //! //! [RFC 3596]: https://tools.ietf.org/html/rfc3596 use std::fmt; use std::net::Ipv6Addr; use std::str::FromStr; use ::bits::{Composable, Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordDa...
else { Ok(None) } } } impl fmt::Display for Aaaa { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.addr.fmt(f) } }
{ Aaaa::parse_always(parser).map(Some) }
conditional_block
mock.rs
// Copyright 2018 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed /...
#[inline] fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { self.fill_bytes(dest); Ok(()) } } #[cfg(test)] mod tests { #[test] #[cfg(feature = "serde1")] fn test_serialization_step_rng() { use super::StepRng; let some_rng = StepRng::new(42, ...
{ impls::fill_bytes_via_next(self, dest); }
identifier_body
mock.rs
// Copyright 2018 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed /...
(&mut self) -> u32 { self.next_u64() as u32 } #[inline] fn next_u64(&mut self) -> u64 { let result = self.v; self.v = self.v.wrapping_add(self.a); result } #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { impls::fill_bytes_via_next(self, dest); ...
next_u32
identifier_name
mock.rs
// Copyright 2018 Developers of the Rand project. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed /...
#[cfg(test)] mod tests { #[test] #[cfg(feature = "serde1")] fn test_serialization_step_rng() { use super::StepRng; let some_rng = StepRng::new(42, 7); let de_some_rng: StepRng = bincode::deserialize(&bincode::serialize(&some_rng).unwrap()).unwrap(); assert_eq!(so...
Ok(()) } }
random_line_split
vec-slices.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// debugger:print padded_tuple.length // check:$8 = 2 // debugger:print padded_tuple.data_ptr[0] // check:$9 = {6, 7} // debugger:print padded_tuple.data_ptr[1] // check:$10 = {8, 9} // debugger:print padded_struct.length // check:$11 = 2 // debugger:print padded_struct.data_ptr[0] // check:$12 = {x = 10, y = 11, z =...
// check:$6 = 2 // debugger:print *((int64_t[2]*)(slice_of_slice.data_ptr)) // check:$7 = {3, 4}
random_line_split
vec-slices.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ x: i16, y: i32, z: i16 } static VECT_SLICE: &'static [i64] = &[64, 65]; static mut MUT_VECT_SLICE: &'static [i64] = &[32]; fn main() { let empty: &[i64] = &[]; let singleton: &[i64] = &[1]; let multiple: &[i64] = &[2, 3, 4, 5]; let slice_of_slice = multiple.slice(1,3); let padded_t...
AStruct
identifier_name
vec-slices.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{()}
identifier_body
issue-26322.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
; let cl = columnline!(); assert_eq!(closure(), (8, 25)); assert_eq!(iflet, (8, 28)); assert_eq!(cl, (13, 30)); let indirect = indirectcolumnline!(); assert_eq!(indirect, (19, 34)); }
{ (0, 0) }
conditional_block
issue-26322.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let closure = || { columnline!() }; let iflet = if let Some(_) = Some(0) { columnline!() } else { (0, 0) }; let cl = columnline!(); assert_eq!(closure(), (8, 25)); assert_eq!(iflet, (8, 28)); assert_eq!(cl, (13, 30)); let indirect = indirectcolumnline!(); ass...
main
identifier_name
issue-26322.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert_eq!(cl, (13, 30)); let indirect = indirectcolumnline!(); assert_eq!(indirect, (19, 34)); }
columnline!() } else { (0, 0) }; let cl = columnline!(); assert_eq!(closure(), (8, 25)); assert_eq!(iflet, (8, 28));
random_line_split
issue-26322.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let closure = || { columnline!() }; let iflet = if let Some(_) = Some(0) { columnline!() } else { (0, 0) }; let cl = columnline!(); assert_eq!(closure(), (8, 25)); assert_eq!(iflet, (8, 28)); assert_eq!(cl, (13, 30)); let indirect = indirectcolumnline!(); assert...
identifier_body
packer-test.rs
extern crate image; extern crate texture_packer; use std::path::Path; use std::fs::File; use texture_packer::texture::Texture; use texture_packer::{ TexturePacker, TexturePackerConfig }; use texture_packer::importer::ImageImporter; use texture_packer::exporter::ImageExporter;
fn main() { let mut config = TexturePackerConfig::default(); config.max_width = MAX_IMAGE_WIDTH; config.max_height = MAX_IMAGE_HEIGHT; config.allow_rotation = false; config.texture_outlines = true; config.border_padding = 2; let ref mut texture_packer = TexturePacker::new_skyline(config); ...
const MAX_IMAGE_WIDTH: u32 = 400; const MAX_IMAGE_HEIGHT: u32 = 400;
random_line_split
packer-test.rs
extern crate image; extern crate texture_packer; use std::path::Path; use std::fs::File; use texture_packer::texture::Texture; use texture_packer::{ TexturePacker, TexturePackerConfig }; use texture_packer::importer::ImageImporter; use texture_packer::exporter::ImageExporter; const MAX_IMAGE_WIDTH: u32 = 400; const ...
let path = "./examples/output/skyline-packer-output.png"; let ref path = Path::new(path); let ref mut file = File::create(path).unwrap(); println!("{} x {}", texture_packer.width(), texture_packer.height()); image.save(file, image::PNG).unwrap(); }
{ let mut config = TexturePackerConfig::default(); config.max_width = MAX_IMAGE_WIDTH; config.max_height = MAX_IMAGE_HEIGHT; config.allow_rotation = false; config.texture_outlines = true; config.border_padding = 2; let ref mut texture_packer = TexturePacker::new_skyline(config); for i ...
identifier_body
packer-test.rs
extern crate image; extern crate texture_packer; use std::path::Path; use std::fs::File; use texture_packer::texture::Texture; use texture_packer::{ TexturePacker, TexturePackerConfig }; use texture_packer::importer::ImageImporter; use texture_packer::exporter::ImageExporter; const MAX_IMAGE_WIDTH: u32 = 400; const ...
() { let mut config = TexturePackerConfig::default(); config.max_width = MAX_IMAGE_WIDTH; config.max_height = MAX_IMAGE_HEIGHT; config.allow_rotation = false; config.texture_outlines = true; config.border_padding = 2; let ref mut texture_packer = TexturePacker::new_skyline(config); for...
main
identifier_name
bubble_sort.rs
//! Module contains pure implementations of bubble sort algorithm. //! //! * `sort` - is non distructive function (does not affects on input sequence) //! * `mut_sort` - function with side effects (modify input sequence) //! //! It's better to use first one in functional style, second - in OOP-style /// Pure implement...
<T: Ord + Clone>(list: &[T]) -> Vec<T> { let mut sorted_list = list.clone().to_vec(); let length = sorted_list.len(); for i in 0..length { let mut swapped = false; for j in 0..length - i - 1 { if sorted_list[j] > sorted_list[j + 1] { sorted_list.swap(j, j + 1); ...
sort
identifier_name
bubble_sort.rs
//! Module contains pure implementations of bubble sort algorithm. //! //! * `sort` - is non distructive function (does not affects on input sequence) //! * `mut_sort` - function with side effects (modify input sequence) //! //! It's better to use first one in functional style, second - in OOP-style /// Pure implement...
mut_sort(&mut test_vector); assert!(is_sorted(&test_vector)); } }
#[test] fn mut_sort_chars() { let mut test_vector = vec!['a', 'r', 'b'];
random_line_split
bubble_sort.rs
//! Module contains pure implementations of bubble sort algorithm. //! //! * `sort` - is non distructive function (does not affects on input sequence) //! * `mut_sort` - function with side effects (modify input sequence) //! //! It's better to use first one in functional style, second - in OOP-style /// Pure implement...
} if swapped == false { break; } } return sorted_list; } /// Pure implementation of bubble sort algorithm. Side-effects version /// Modifies input sequense /// /// # Examples /// /// ``` /// use algorithms::sorts::bubble_sort::mut_sort; /// use algorithms::sorts::utils::is_...
{ sorted_list.swap(j, j + 1); swapped = true; }
conditional_block
bubble_sort.rs
//! Module contains pure implementations of bubble sort algorithm. //! //! * `sort` - is non distructive function (does not affects on input sequence) //! * `mut_sort` - function with side effects (modify input sequence) //! //! It's better to use first one in functional style, second - in OOP-style /// Pure implement...
#[cfg(test)] mod tests { use super::*; use super::super::utils::is_sorted; #[test] fn sort_numbers() { let empty_vec: Vec<i32> = Vec::new(); assert!(is_sorted(&sort(&[0, 5, 3, 2, 2]))); assert!(is_sorted(&sort(&empty_vec))); assert!(is_sorted(&sort(&[-1, -5, -10, 105])...
{ for n in (0..(list.len() as isize + 1)).rev() { for m in 1..(n as usize) { if list[m] < list[m - 1] { list.swap(m, m - 1); } } } }
identifier_body
spacing_after.rs
extern crate std as ruststd; use core::hash::{self, Hash}; use core::intrinsics::{arith_offset, assume}; use core::iter::FromIterator; use core::mem; use core::ops::{Index, IndexMut}; const CAPACITY: usize = 2 * B - 1; fn foo(a: i32, b: str, c: i32, d: f32) -> () { let mut e: &'static [str] = "abcd"; let mut...
w += 1; } r += 1; } self.truncate(w); } } } pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {} impl<T: Clone> Clone for Vec<T> { fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) } fn clone(&self) ->...
}
random_line_split
spacing_after.rs
extern crate std as ruststd; use core::hash::{self, Hash}; use core::intrinsics::{arith_offset, assume}; use core::iter::FromIterator; use core::mem; use core::ops::{Index, IndexMut}; const CAPACITY: usize = 2 * B - 1; fn foo(a: i32, b: str, c: i32, d: f32) -> () { let mut e: &'static [str] = "abcd"; let mut...
} impl<T: Hash> Hash for Vec<T> { fn hash<H: hash::Hasher>(&self, state: &mut H) { Hash::hash(&**self, state) } } impl<T> Index<usize> for Vec<T> { type Output = T; fn index(&self, index: usize) -> &T { &(**self)[index] } } impl<T> IndexMut<usize> for Vec<T> { fn index_mut(&...
{ self.truncate(other.len()); let len = self.len(); self.clone_from_slice(&other[..len]); self.extend_from_slice(&other[len..]); }
identifier_body
spacing_after.rs
extern crate std as ruststd; use core::hash::{self, Hash}; use core::intrinsics::{arith_offset, assume}; use core::iter::FromIterator; use core::mem; use core::ops::{Index, IndexMut}; const CAPACITY: usize = 2 * B - 1; fn foo(a: i32, b: str, c: i32, d: f32) -> () { let mut e: &'static [str] = "abcd"; let mut...
<T: Clone>(elem: T, n: usize) -> Vec<T> {} impl<T: Clone> Clone for Vec<T> { fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) } fn clone(&self) -> Vec<T> { ::slice::to_vec(&**self) } fn clone_from(&mut self, other: &Vec<T>) { self.truncate(other.len()); let len =...
from_elem
identifier_name
shootout-k-nucleotide.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 ...
{ if self.items.get(index as uint).is_none() { let mut entry = box Entry { code: key, count: 0, next: None, }; c.f(entry); *self.items.get_mut(index as uint) = Some(entry); ...
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) { let index = key.hash() % (TABLE_SIZE as u64);
random_line_split
shootout-k-nucleotide.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, c: u8) -> Code { Code((self.hash() << 2) + (pack_symbol(c) as u64)) } fn rotate(&self, c: u8, frame: uint) -> Code { Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1)) } fn pack(string: &str) -> Code { string.bytes().fold(Code(0u64), |a, b| a.push_char(b)) ...
push_char
identifier_name
fwz_est.rs
%-------------------------------------------------------------% % Declarations: % names are separated by a comma, a space or both % "..." are used to describe the preceding variable %-------------------------------------------------------------% %Endogenous variables endogenous X, "Output ga...
% the relationship between the two is given in the model % observable variables varobs R, X, PAI model % auxiliary parameters # beta=1/(1+beta_trans/100); % Main equations % N.B: time is denoted by () as in dynare or by {}. Below, we use the {} notation X = X{+1}-tau*(R-PAI{+1})+ZD; PAI = beta*...
kappa, "$\kappa $", rhor, "$\rho _{r}$", rhod, "$\rho _{d}$" rhos, "$\rho _{s}$" % N.B: we have removed the transition probabilities from the list of % parameters since in some cases they will not matter % N.B: we replace beta by beta_trans, just to make optimization easier
random_line_split
serialize-deserialize-state-format-old.rs
/* Copyright © 2016 Zetok Zalbavar <zexavexxe@gmail.com> This file is part of Tox. Tox is libre 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...
let bytes = include_bytes!("state-format-old-data/profile-with-contacts.tox"); let profile_b = State::from_bytes(bytes).unwrap().to_bytes(); assert_eq!(&bytes[..profile_b.len()], profile_b.as_slice()); // c-toxcore appends `0`s after EOF because reasons for b in &bytes[profile_b.len()..] { a...
state_format_to_and_from_bytes() {
identifier_name
serialize-deserialize-state-format-old.rs
/* Copyright © 2016 Zetok Zalbavar <zexavexxe@gmail.com> This file is part of Tox.
Tox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License alo...
Tox is libre 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 version.
random_line_split
serialize-deserialize-state-format-old.rs
/* Copyright © 2016 Zetok Zalbavar <zexavexxe@gmail.com> This file is part of Tox. Tox is libre 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...
let bytes = include_bytes!("state-format-old-data/profile-with-contacts.tox"); let profile_b = State::from_bytes(bytes).unwrap().to_bytes(); assert_eq!(&bytes[..profile_b.len()], profile_b.as_slice()); // c-toxcore appends `0`s after EOF because reasons for b in &bytes[profile_b.len()..] { asse...
identifier_body
lib.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub mod back { pub use rustc_back::abi; pub use rustc_back::archive; pub use rustc_back::arm; pub use rustc_back::mips; pub use rustc_back::mipsel; pub use rustc_back::rpath; pub use rustc_back::svh; pub use rustc_back::target_strs; pub use rustc_back::x86; pub use rustc_back::x...
random_line_split
node.rs
//! The sure stream. //! //! The sure stream represents a linearization of a SureTree. By keeping //! representations as iterators across SureNodes instead of keeping an //! entire tree in memory, we can process larger filesystem trees, using //! temporary space on the hard disk instead of using memory. use crate::{su...
fn fixed<I>(inp: &mut I, exp: &[u8]) -> Result<()> where I: Iterator<Item = io::Result<Vec<u8>>>, { match inp.next() { Some(Ok(ref text)) if &text[..] == exp => Ok(()), Some(Ok(ref text)) => Err(Error::UnexpectedLine( String::from_utf8_lossy(text).into_owned(), String::...
{ let rd = BufReader::new(rd); let mut lines = rd.split(b'\n'); fixed(&mut lines, b"asure-2.0")?; fixed(&mut lines, b"-----")?; Ok(ReadIterator { lines, depth: 0, done: false, }) }
identifier_body
node.rs
//! The sure stream. //! //! The sure stream represents a linearization of a SureTree. By keeping //! representations as iterators across SureNodes instead of keeping an //! entire tree in memory, we can process larger filesystem trees, using //! temporary space on the hard disk instead of using memory. use crate::{su...
} } pub fn is_file(&self) -> bool { matches!(self, SureNode::File {.. }) } pub fn is_leave(&self) -> bool { matches!(self, SureNode::Leave) } pub fn is_sep(&self) -> bool { matches!(self, SureNode::Sep) } pub fn needs_hash(&self) -> bool { matc...
pub fn is_reg_file(&self) -> bool { match self { SureNode::File { atts, .. } => atts["kind"] == "file", _ => false,
random_line_split
node.rs
//! The sure stream. //! //! The sure stream represents a linearization of a SureTree. By keeping //! representations as iterators across SureNodes instead of keeping an //! entire tree in memory, we can process larger filesystem trees, using //! temporary space on the hard disk instead of using memory. use crate::{su...
(&self) -> Option<&AttMap> { match self { SureNode::File { ref atts,.. } => Some(atts), SureNode::Enter { ref atts,.. } => Some(atts), _ => None, } } /// Access the nodes attributes mutably. pub fn atts_mut(&mut self) -> Option<&mut AttMap> { matc...
atts
identifier_name
main.rs
#[macro_use] extern crate bitflags; extern crate libc; extern crate websocket; extern crate yassy; extern crate midi; mod jack; mod jack_plugin; use jack::*; use std::time::Duration; use std::ffi::CString; // use std::thread; // use websocket::{Server, Message, Sender, Receiver}; // use websocket::message::Type; // u...
(*plugin).midievent(&*event.buffer); ievent = ievent + 1; // Need to check if ievent < event_count before next call to // jack_midi_event_get()? Don't think so, but see // https://github.com/jackaudio/example-clients/blob/master/midisine.c ...
{ unsafe { let plugin = ptr as *mut Plugin; let inport = &(*plugin).in_port; let outport = &(*plugin).output; let buf = jack_port_get_buffer(inport.handle, jack_nframes_t); let out = jack_port_get_buffer(outport.handle, jack_nframes_t) as *mut f32; let event_count = ...
identifier_body
main.rs
#[macro_use] extern crate bitflags; extern crate libc; extern crate websocket; extern crate yassy; extern crate midi; mod jack; mod jack_plugin; use jack::*; use std::time::Duration; use std::ffi::CString; // use std::thread; // use websocket::{Server, Message, Sender, Receiver}; // use websocket::message::Type; // u...
() { // CString must stay alive after pointer is obtained // see http://stackoverflow.com/questions/38007154/jack-audio-client-name-longer-than-4-characters-breaks-client let name = CString::new("yassyhost").unwrap(); let mut p = Plugin::new(&name); p.initialize(); p.set_fs(); p.connect(); ...
main
identifier_name
main.rs
#[macro_use] extern crate bitflags; extern crate libc; extern crate websocket; extern crate yassy; extern crate midi; mod jack; mod jack_plugin; use jack::*; use std::time::Duration; use std::ffi::CString; // use std::thread; // use websocket::{Server, Message, Sender, Receiver}; // use websocket::message::Type; // u...
let amp = (*plugin).get_amp(); *out.offset(i as isize) = amp; } } 0 } pub type Plugin<'a> = jack_plugin::jack_plugin<'a>; fn main() { // CString must stay alive after pointer is obtained // see http://stackoverflow.com/questions/38007154/jack-audio-client-name-longer-t...
{ (*plugin).midievent(&*event.buffer); ievent = ievent + 1; // Need to check if ievent < event_count before next call to // jack_midi_event_get()? Don't think so, but see // https://github.com/jackaudio/example-clients/blob/master/midisine....
conditional_block
main.rs
#[macro_use] extern crate bitflags; extern crate libc; extern crate websocket; extern crate yassy; extern crate midi; mod jack; mod jack_plugin; use jack::*; use std::time::Duration;
// use websocket::message::Type; // use websocket::header::WebSocketProtocol; // use std::ffi::CString; // use std::ffi::CStr; // use std::sync::{Arc, Mutex}; // use std::sync::mpsc; // use std::ptr; // use jack_plugin; // use yassy::Plugin; extern "C" fn process(jack_nframes_t: u32, ptr: *mut libc::c_void) -> isize ...
use std::ffi::CString; // use std::thread; // use websocket::{Server, Message, Sender, Receiver};
random_line_split
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS}; // https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMEN...
.add(b']') .add(b'^') .add(b'|'); pub const HG_ENCODE_SET: &AsciiSet = &USERINFO.add(b','); pub fn percent_encode(input: &str) -> String { // This encode set doesn't exactly match what Python's urllib does, but it's // close enough and importantly it encodes '=' which is the only important // one...
.add(b';') .add(b'=') .add(b'@') .add(b'[') .add(b'\\')
random_line_split
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS}; // https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMEN...
{ // This encode set doesn't exactly match what Python's urllib does, but it's // close enough and importantly it encodes '=' which is the only important // one. utf8_percent_encode(input, HG_ENCODE_SET).collect::<String>() }
identifier_body
utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS}; // https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMEN...
(input: &str) -> String { // This encode set doesn't exactly match what Python's urllib does, but it's // close enough and importantly it encodes '=' which is the only important // one. utf8_percent_encode(input, HG_ENCODE_SET).collect::<String>() }
percent_encode
identifier_name
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
assert!(is_aligned(u64_align, &x.tB)); assert!(variant_data_is_aligned(u64_align, &x.tB)); let x = mk_rec(22u64, 23u32); assert!(is_aligned(u64_align, &x.tA)); assert!(variant_data_is_aligned(u64_align, &x.tA)); assert!(is_aligned(u64_align, &x.tB)); assert!(variant_data_is_aligned(4, &x.tB...
let u64_align = std::mem::min_align_of::<u64>(); let x = mk_rec(22u64, 23u64); assert!(is_aligned(u64_align, &x.tA)); assert!(variant_data_is_aligned(u64_align, &x.tA));
random_line_split
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<A,B> { VarA(A), VarB(B), } struct Rec<A,B> { chA: u8, tA: Tag<A,B>, chB: u8, tB: Tag<A,B>, } fn mk_rec<A,B>(a: A, b: B) -> Rec<A,B> { Rec { chA:0, tA:Tag::VarA(a), chB:1, tB:Tag::VarB(b) } } fn is_aligned<A>(amnt: usize, u: &A) -> bool { let p: usize = unsafe { mem::transmute(u) }; ...
Tag
identifier_name
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { let u64_align = std::mem::min_align_of::<u64>(); let x = mk_rec(22u64, 23u64); assert!(is_aligned(u64_align, &x.tA)); assert!(variant_data_is_aligned(u64_align, &x.tA)); assert!(is_aligned(u64_align, &x.tB)); assert!(variant_data_is_aligned(u64_align, &x.tB)); let x = mk_r...
{ match u { &Tag::VarA(ref a) => is_aligned(amnt, a), &Tag::VarB(ref b) => is_aligned(amnt, b) } }
identifier_body
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
DedicatedWorkerGlobalScope::run_worker_scope( worker_url, global.pipeline(), global.mem_profiler_chan(), global.devtools_chan(), worker_ref, resource_task, global.script_chan(), sender, receiver); Ok(worker) } pub fn handle_message(address: TrustedWorkerAddress, ...
{ let pipeline_id = global.pipeline(); let (devtools_sender, _) = channel(); let title = format!("Worker for {}", worker_url); let page_info = DevtoolsPageInfo { title: title, url: worker_url.clone(), }; let worker_i...
conditional_block
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
event.fire(target); } } impl<'a> WorkerMethods for &'a Worker { fn PostMessage(self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { let data = try!(StructuredCloneData::write(cx, message)); let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone()); ...
message, filename, lineno, colno, error.handle()); let event = EventCast::from_ref(errorevent.r());
random_line_split
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
{ addr: TrustedWorkerAddress, data: StructuredCloneData, } impl WorkerMessageHandler { pub fn new(addr: TrustedWorkerAddress, data: StructuredCloneData) -> WorkerMessageHandler { WorkerMessageHandler { addr: addr, data: data, } } } impl Runnable for WorkerMessa...
WorkerMessageHandler
identifier_name
worker.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::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe...
} impl Runnable for WorkerMessageHandler { fn handler(self: Box<WorkerMessageHandler>) { let this = *self; Worker::handle_message(this.addr, this.data); } } pub struct WorkerEventHandler { addr: TrustedWorkerAddress, } impl WorkerEventHandler { pub fn new(addr: TrustedWorkerAddress) ...
{ WorkerMessageHandler { addr: addr, data: data, } }
identifier_body
syntax.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub mod ext { pub mod asm; pub mod base; pub mod expand; pub mod quote; pub mod deriving; pub mod build; pub mod tt { pub mod transcribe; pub mod macro_parser; pub mod macro_rules; } pub mod cfg; pub mod fmt; pub mod format; pub mod env; ...
pub mod pp; pub mod pprust; }
random_line_split
flex_box.rs
//! Test module for `cripes::util::flex_box`, which provides flexibly-sized //! reusable boxes. use std; use cripes::util::flex_box::*; #[test] /// Test that FlexBox works for simple value types. fn test_simple_value() { let mut b = FlexBox::new(); { let x = b.store(3u8); println!("{:?}", x);...
} let mut b = FlexBox::new(); { let x = b.store(HasDrop(ran_drop.clone())); assert!( 0 == ran_drop.borrow().load(Ordering::SeqCst) ); drop(x); assert!( 1 == ran_drop.borrow().load(Ordering::SeqCst) ); } ran_drop.borrow().store(0, Ordering::SeqCst); { l...
{ println!("Goodbye, World!"); self.0.borrow_mut().fetch_add(1, Ordering::SeqCst); }
identifier_body
flex_box.rs
//! Test module for `cripes::util::flex_box`, which provides flexibly-sized //! reusable boxes. use std; use cripes::util::flex_box::*; #[test] /// Test that FlexBox works for simple value types. fn test_simple_value() { let mut b = FlexBox::new(); { let x = b.store(3u8); println!("{:?}", x);...
() { use std::rc::Rc; use std::ops::Drop; use std::mem::drop; use std::cell::RefCell; use std::sync::atomic::{AtomicUsize,Ordering}; let ran_drop = Rc::new(RefCell::new(AtomicUsize::new(0))); struct HasDrop(Rc<RefCell<AtomicUsize>>); impl Drop for HasDrop { fn drop(&mut self) {...
test_with_drop
identifier_name
flex_box.rs
//! Test module for `cripes::util::flex_box`, which provides flexibly-sized //! reusable boxes. use std; use cripes::util::flex_box::*; #[test] /// Test that FlexBox works for simple value types. fn test_simple_value() { let mut b = FlexBox::new(); { let x = b.store(3u8); println!("{:?}", x);...
for x in it { println!("{:?} ", x); } } } #[test] /// Check that we can store items in a FlexBox indirectly. This is mostly /// a compile-time check. fn test_store_indirect() { let mut b = FlexBox::new(); for x in store_and_return_iterator::<()>(&mut b) { println!("{...
{ let u = vec![1, 2, 3, 4]; let it: Ref<Iterator<Item=_>> = b.store(u.iter());
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFie...
reg.register_early_lint_pass(box lints::ban::BanPass); reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted); reg.register_attribute("must_root".to_string(), Whitelisted); register_clippy(reg); } #[cfg(feature = "clippy")] fn register_clippy(reg: &mut Registry) { ::clippy_lints...
reg.register_late_lint_pass(box lints::unrooted_must_root::UnrootedPass::new());
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFie...
#[cfg(not(feature = "clippy"))] fn register_clippy(_reg: &mut Registry) { }
{ ::clippy_lints::register_plugins(reg); }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Servo's compiler plugin/macro crate //! //! Attributes this crate provides: //! //! - `#[derive(DenyPublicFie...
(reg: &mut Registry) { reg.register_syntax_extension( Symbol::intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct)); reg.register_late_lint_pass(box lints::unrooted_must_root::UnrootedPass::new()); reg.register_early_lint_pass(box lints::ban::BanPass); reg.register_at...
plugin_registrar
identifier_name
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use canvas::{...
{ Profiler, TextureCacheDebug, RenderTargetDebug, } /// Events that the windowing system sends to Servo. #[derive(Clone)] pub enum WindowEvent { /// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps /// by another Servo subsystem). /// /// FIXME(pcwal...
WebRenderDebugOption
identifier_name
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use canvas::{...
}
{ let fb_height = self.framebuffer.height; let mut view = self.viewport.clone(); view.origin.y = fb_height - view.origin.y - view.size.height; DeviceIntRect::from_untyped(&view.to_untyped()) }
identifier_body
windowing.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/. */ //! Abstract windowing methods. The concrete implementations of these can be found in `platform/`. use canvas::{...
WindowEvent::CloseBrowser(..) => write!(f, "CloseBrowser"), WindowEvent::SelectBrowser(..) => write!(f, "SelectBrowser"), WindowEvent::ToggleWebRenderDebug(..) => write!(f, "ToggleWebRenderDebug"), WindowEvent::CaptureWebRender => write!(f, "CaptureWebRender"), ...
WindowEvent::NewBrowser(..) => write!(f, "NewBrowser"), WindowEvent::SendError(..) => write!(f, "SendError"),
random_line_split
account.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI...
() -> Self { Self::new(None) } } impl Into<FullId> for ClientKeys { fn into(self) -> FullId { let enc_sk = (*self.enc_sk).clone(); let sign_sk = (*self.sign_sk).clone(); FullId::with_keys((self.enc_pk, enc_sk), (self.sign_pk, sign_sk)) } } #[cfg(test)] mod tests { use ...
default
identifier_name
account.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI...
pwhash::derive_key( output, input, &salt, pwhash::OPSLIMIT_INTERACTIVE, pwhash::MEMLIMIT_INTERACTIVE, ) .map(|_| ()) .map_err(|_| CoreError::UnsuccessfulPwHash) } } /// Client signing and encryption keypairs #[derive(Clone, ...
}
random_line_split
account.rs
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI...
}
{ let account = unwrap!(Account::new(ClientKeys::new(None))); let password = b"impossible to guess"; let pin = b"1000"; let encrypted = unwrap!(account.encrypt(password, pin)); let encoded = unwrap!(serialise(&account)); assert!(!encrypted.is_empty()); assert_ne...
identifier_body
message.rs
use std::error::Error; // general notifications define_msg! { pub CannotReadConfig: "ko" => "프로젝트에서 `kailua.json`이나 `.vscode/kailua.json`을 읽을 수 없습니다. \ 이번 세션에서 타입 체크가 비활성화됩니다.", _ => "Cannot read `kailua.json` or `.vscode/kailua.json` in the project; \ type checking is disabled fo...
} define_msg! { pub OmittedSelfLabel: "ko" => "<생략됨>", _ => "<omitted>", }
random_line_split
field_benchmark.rs
#[macro_use] extern crate criterion; use criterion::{black_box, Bencher, Criterion}; use oppai_field::construct_field::construct_moves; use oppai_field::field::{self, Field, Pos}; use oppai_field::player::Player; use oppai_field::zobrist::Zobrist; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xoshiro::Xo...
} for _ in 0..field.moves_count() { field.undo(); } field }); } fn game_without_surroundings(c: &mut Criterion) { let (width, height, moves) = construct_moves( " .............. .aDFgjMOprUWx. .BceHKlnQStvY. .............. ", ); c.bench_function("game_without_surroundin...
field.put_point(pos, player); }
random_line_split
field_benchmark.rs
#[macro_use] extern crate criterion; use criterion::{black_box, Bencher, Criterion}; use oppai_field::construct_field::construct_moves; use oppai_field::field::{self, Field, Pos}; use oppai_field::player::Player; use oppai_field::zobrist::Zobrist; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xoshiro::Xo...
fn game(bencher: &mut Bencher, width: u32, height: u32, moves: Vec<(Player, Pos)>) { let mut rng = Xoshiro256PlusPlus::seed_from_u64(SEED_1); let zobrist = Arc::new(Zobrist::new(field::length(width, height) * 2, &mut rng)); bencher.iter(|| { let mut field = Field::new(width, height, zobrist.clone()); fo...
{ c.bench_function("random_game_3", |bencher| random_game(bencher, 30, 30, SEED_3)); }
identifier_body
field_benchmark.rs
#[macro_use] extern crate criterion; use criterion::{black_box, Bencher, Criterion}; use oppai_field::construct_field::construct_moves; use oppai_field::field::{self, Field, Pos}; use oppai_field::player::Player; use oppai_field::zobrist::Zobrist; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xoshiro::Xo...
(c: &mut Criterion) { c.bench_function("random_game_1", |bencher| random_game(bencher, 30, 30, SEED_1)); } fn random_game_2(c: &mut Criterion) { c.bench_function("random_game_2", |bencher| random_game(bencher, 30, 30, SEED_2)); } fn random_game_3(c: &mut Criterion) { c.bench_function("random_game_3", |bencher| ...
random_game_1
identifier_name
field_benchmark.rs
#[macro_use] extern crate criterion; use criterion::{black_box, Bencher, Criterion}; use oppai_field::construct_field::construct_moves; use oppai_field::field::{self, Field, Pos}; use oppai_field::player::Player; use oppai_field::zobrist::Zobrist; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xoshiro::Xo...
} for _ in 0..field.moves_count() { field.undo(); } field }); } fn game_without_surroundings(c: &mut Criterion) { let (width, height, moves) = construct_moves( " .............. .aDFgjMOprUWx. .BceHKlnQStvY. .............. ", ); c.bench_function("game_without_surroundi...
{ field.put_point(pos, player); }
conditional_block
mod.rs
mod codec; mod handshake; pub use self::codec::ApCodec; pub use self::handshake::handshake; use std::io::{self, ErrorKind}; use std::net::ToSocketAddrs; use futures_util::{SinkExt, StreamExt}; use protobuf::{self, Message, ProtobufError}; use thiserror::Error; use tokio::net::TcpStream; use tokio_util::codec::Framed...
#[derive(Debug, Error)] pub enum AuthenticationError { #[error("Login failed with reason: {}", login_error_message(.0))] LoginFailed(ErrorCode), #[error("Authentication failed: {0}")] IoError(#[from] io::Error), } impl From<ProtobufError> for AuthenticationError { fn from(e: ProtobufError) -> Self...
}
random_line_split
mod.rs
mod codec; mod handshake; pub use self::codec::ApCodec; pub use self::handshake::handshake; use std::io::{self, ErrorKind}; use std::net::ToSocketAddrs; use futures_util::{SinkExt, StreamExt}; use protobuf::{self, Message, ProtobufError}; use thiserror::Error; use tokio::net::TcpStream; use tokio_util::codec::Framed...
(e: ProtobufError) -> Self { io::Error::new(ErrorKind::InvalidData, e).into() } } impl From<APLoginFailed> for AuthenticationError { fn from(login_failure: APLoginFailed) -> Self { Self::LoginFailed(login_failure.get_error_code()) } } pub async fn connect(addr: String, proxy: Option<&Url>)...
from
identifier_name
self-impl.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// Test that unsupported uses of `Self` in impls don't crash struct Bar; trait Foo { type Baz; } trait SuperFoo { type SuperBaz; } impl Foo for Bar { type Baz = bool; } impl SuperFoo for Bar { type SuperBaz = bool; } impl Bar { fn f() { let _: <Self>::Baz = true; //~^ ERROR amb...
random_line_split
self-impl.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
; trait Foo { type Baz; } trait SuperFoo { type SuperBaz; } impl Foo for Bar { type Baz = bool; } impl SuperFoo for Bar { type SuperBaz = bool; } impl Bar { fn f() { let _: <Self>::Baz = true; //~^ ERROR ambiguous associated type let _: Self::Baz = true; //~^ ERR...
Bar
identifier_name
macros.rs
macro_rules! irq_handler { ($idt:expr, $irq:expr, $irq_handler:ident) => {{ extern "x86-interrupt" fn base_handler(_: &mut ExceptionStackFrame) { // Base handler. Push and pop context between call to handler implementation. unsafe { asm!("push rbp ...
$idt.interrupts[$irq].set_handler_fn(base_handler); }} }
} }
random_line_split
attr_iterator.rs
// Copyright 2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use glib::translate::*; use glib_sys; use pango_sys; use AttrIterator; use Attribute; use FontDes...
( &mut self, desc: &mut FontDescription, language: Option<&Language>, extra_attrs: &[&Attribute], ) { unsafe { let stash_vec: Vec<_> = extra_attrs.iter().rev().map(|v| v.to_glib_none()).collect(); let mut list: *mut glib_sys::GSList = ptr::null_mut(); ...
get_font
identifier_name
attr_iterator.rs
// Copyright 2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use glib::translate::*; use glib_sys; use pango_sys; use AttrIterator; use Attribute; use FontDes...
}
); } }
random_line_split
attr_iterator.rs
// Copyright 2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> use glib::translate::*; use glib_sys; use pango_sys; use AttrIterator; use Attribute; use FontDes...
}
{ unsafe { let stash_vec: Vec<_> = extra_attrs.iter().rev().map(|v| v.to_glib_none()).collect(); let mut list: *mut glib_sys::GSList = ptr::null_mut(); for stash in &stash_vec { list = glib_sys::g_slist_prepend(list, Ptr::to(stash.0)); } ...
identifier_body
paging.rs
//! Definitions for paging structures use ::core::mem::size_of; use arch::x86_64::x86::paging; pub trait Level { type Table; fn new() -> Self::Table; } trait ParentLevel: Level { type Child; } pub enum PML4Table {} pub enum PDPTTable {} pub enum PDTable {} pub enum PTTable {} impl Level for PML4Table {...
pub struct Table<L: Level> { tables: L::Table, } pub type PML4 = Table<PML4Table>; pub type PDPT = Table<PDPTTable>; pub type PD = Table<PDTable>; pub type PT = Table<PTTable>; impl<L: Level> Table<L> { pub fn mem_align() -> usize { size_of::<L::Table>() } } impl<L: Level> Default for Table<L> {...
fn new() -> paging::PT { [paging::PTEntry::empty(); 512] } }
random_line_split
paging.rs
//! Definitions for paging structures use ::core::mem::size_of; use arch::x86_64::x86::paging; pub trait Level { type Table; fn new() -> Self::Table; } trait ParentLevel: Level { type Child; } pub enum PML4Table {} pub enum PDPTTable {} pub enum PDTable {} pub enum PTTable {} impl Level for PML4Table {...
}
{ Table { tables: L::new() } }
identifier_body
paging.rs
//! Definitions for paging structures use ::core::mem::size_of; use arch::x86_64::x86::paging; pub trait Level { type Table; fn new() -> Self::Table; } trait ParentLevel: Level { type Child; } pub enum PML4Table {} pub enum PDPTTable {} pub enum PDTable {} pub enum PTTable {} impl Level for PML4Table {...
() -> paging::PML4 { [paging::PML4Entry::empty(); 512] } } impl Level for PDPTTable { type Table = paging::PDPT; fn new() -> paging::PDPT { [paging::PDPTEntry::empty(); 512] } } impl Level for PDTable { type Table = paging::PD; fn new() -> paging::PD { [paging::PDEntry:...
new
identifier_name
border.rs
// Copyright 2013-2017, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use std::fmt; use std::ops; glib_wrapper! { #[derive(Pa...
() -> Border { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_border_new()) } } } impl Default for Border { fn default() -> Self { Self::new() } } impl fmt::Debug for Border { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Er...
new
identifier_name
border.rs
// Copyright 2013-2017, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use std::fmt; use std::ops; glib_wrapper! { #[derive(Pa...
fn deref_mut(&mut self) -> &mut Self::Target { &mut (*self.0) } } impl Border { pub fn new() -> Border { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::gtk_border_new()) } } } impl Default for Border { fn default() -> Self { Sel...
impl ops::DerefMut for Border {
random_line_split
border.rs
// Copyright 2013-2017, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use std::fmt; use std::ops; glib_wrapper! { #[derive(Pa...
} impl fmt::Debug for Border { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { fmt.debug_struct("Border") .field("left", &self.left) .field("right", &self.right) .field("top", &self.top) .field("bottom", &self.bottom) .finish() ...
{ Self::new() }
identifier_body
index.rs
use super::asc::Asc;
use super::desc::Desc; use crate::cmd; use crate::proto::{Command, Query}; use serde::Serialize; #[derive(Debug, Clone)] pub struct Index(pub(crate) Command); #[derive(Serialize)] struct Inner<'a> { index: Query<'a>, } pub trait Arg { fn arg(self) -> cmd::Arg<()>; } impl<T> Arg for T where T: Into<Strin...
random_line_split
index.rs
use super::asc::Asc; use super::desc::Desc; use crate::cmd; use crate::proto::{Command, Query}; use serde::Serialize; #[derive(Debug, Clone)] pub struct Index(pub(crate) Command); #[derive(Serialize)] struct Inner<'a> { index: Query<'a>, } pub trait Arg { fn arg(self) -> cmd::Arg<()>; } impl<T> Arg for T wh...
(self) -> cmd::Arg<()> { let Asc(index) = self; Command::from_json(Inner { index: Query(&index), }) .into_arg() } } impl Arg for Desc { fn arg(self) -> cmd::Arg<()> { let Desc(index) = self; Command::from_json(Inner { index: Query(&index), ...
arg
identifier_name
adding_prob_src.rs
extern crate rand; use rand::distributions::{Range, IndependentSample}; use af; use af::{Array, Dim4, MatProp, DType}; use std::cell::{RefCell, Cell}; use initializations::uniform; use utils; use data::{Data, DataSource, DataParams, Normalize, Shuffle}; pub struct AddingProblemSource { pub params: DataParams, pu...
self.iter.set(self.iter.get() + 1); batch } fn info(&self) -> DataParams { self.params.clone() } fn get_test_iter(&self, num_batch: u64) -> Data { self.get_train_iter(num_batch) } fn get_validation_iter(&self, num_batch: u64) -> Option<Data> { Some( self.get_train_iter(num_batch)) }...
let current_iter = self.params.current_epoch.get(); if self.iter.get() == self.params.num_samples as u64/ num_batch as u64 { self.params.current_epoch.set(current_iter + 1); self.iter.set(0); }
random_line_split