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
lib.rs
pub mod car; use car::car_factory::CarFactory; use car::car_type::{Body, Colour}; use car::Car; pub struct
{ cars: Vec<Car>, car_factory: CarFactory, } impl Parking { pub fn new() -> Parking { Parking { cars: Vec::new(), car_factory: CarFactory::new(), } } pub fn add_car( &mut self, license_plate: &str, parking_place_number: u8, b...
Parking
identifier_name
lib.rs
pub mod car; use car::car_factory::CarFactory; use car::car_type::{Body, Colour}; use car::Car; pub struct Parking { cars: Vec<Car>, car_factory: CarFactory, } impl Parking { pub fn new() -> Parking { Parking { cars: Vec::new(), car_factory: CarFactory::new(), } ...
) { self.cars.push(Car::new( license_plate.to_string(), parking_place_number, self.car_factory.get_car_type_id(body, colour), )); } pub fn print(&mut self) { for car in &self.cars { car.print(self.car_factory.get_car_type(car.car_type_...
license_plate: &str, parking_place_number: u8, body: Body, colour: Colour,
random_line_split
lib.rs
pub mod car; use car::car_factory::CarFactory; use car::car_type::{Body, Colour}; use car::Car; pub struct Parking { cars: Vec<Car>, car_factory: CarFactory, } impl Parking { pub fn new() -> Parking { Parking { cars: Vec::new(), car_factory: CarFactory::new(), } ...
}
{ for car in &self.cars { car.print(self.car_factory.get_car_type(car.car_type_id).unwrap()); } println!("\nNumber of cars: {}", self.cars.len()); self.car_factory.print(); }
identifier_body
glcommon.rs
use core::prelude::*; use opengles::gl2; use opengles::gl2::{GLuint, GLint}; use core::borrow::{Cow, IntoCow}; use collections::string::String; pub type GLResult<T> = Result<T, MString>; pub type MString = Cow<'static, String, str>; fn get_gl_error_name(error: u32) -> &'static str { match error { gl2::NO_...
gl2::glVertexAttribPointer($handle, $count, gl2::FLOAT, false as ::opengles::gl2::GLboolean, mem::size_of_val(firstref) as i32, // XXX this actually derefences firstref and is completely unsafe // is there better way to do offsetof in rust? there ought to be ...
random_line_split
glcommon.rs
use core::prelude::*; use opengles::gl2; use opengles::gl2::{GLuint, GLint}; use core::borrow::{Cow, IntoCow}; use collections::string::String; pub type GLResult<T> = Result<T, MString>; pub type MString = Cow<'static, String, str>; fn get_gl_error_name(error: u32) -> &'static str { match error { gl2::NO_...
<Init> { pub val: Init } pub trait FillDefaults<Init> { type Unfilled; fn fill_defaults(unfilled: <Self as FillDefaults<Init>>::Unfilled) -> Defaults<Init>; } pub trait UsingDefaults<Init> { type Defaults; //fn fill_defaults(Init) -> <Self as UsingDefaults<Init>>::Defaults; fn maybe_init(Init)...
Defaults
identifier_name
glcommon.rs
use core::prelude::*; use opengles::gl2; use opengles::gl2::{GLuint, GLint}; use core::borrow::{Cow, IntoCow}; use collections::string::String; pub type GLResult<T> = Result<T, MString>; pub type MString = Cow<'static, String, str>; fn get_gl_error_name(error: u32) -> &'static str { match error { gl2::NO_...
pub fn load_shader(shader_type: gl2::GLenum, source: &str) -> GLResult<GLuint> { let shader = gl2::create_shader(shader_type); if shader!= 0 { gl2::shader_source(shader, [source.as_bytes()].as_slice()); gl2::compile_shader(shader); let compiled = gl2::get_shader_iv(shader, gl2::COMPILE...
{ let (err, result) = match gl2::check_framebuffer_status(gl2::FRAMEBUFFER) { gl2::FRAMEBUFFER_COMPLETE => ("FRAMEBUFFER_COMPLETE", true), gl2::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => ("FRAMEBUFFER_INCOMPLETE_ATTACHMENT", false), gl2::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => ("FRAMEBUFFER_I...
identifier_body
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session ...
(&mut self, irq: u8) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_irq(irq); } scheduler::end_no_ints(reenable); } pub unsafe fn on_poll(&mut self) { let reenable = scheduler::start_no_ints(); for mut ite...
on_irq
identifier_name
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session
pub fn new() -> Box<Self> { box Session { items: Vec::new(), } } pub unsafe fn on_irq(&mut self, irq: u8) { let reenable = scheduler::start_no_ints(); for mut item in self.items.iter_mut() { item.on_irq(irq); } scheduler::end_no_ints(r...
random_line_split
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session ...
} } None } } }
{ if url.scheme().len() == 0 { let mut list = String::new(); for item in self.items.iter() { let scheme = item.scheme(); if !scheme.is_empty() { if !list.is_empty() { list = list + "\n" + scheme; ...
identifier_body
session.rs
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use scheduler; use schemes::KScheme; use schemes::{Resource, Url, VecResource}; /// A session pub struct Session { /// The scheme items pub items: Vec<Box<KScheme>>, } impl Session { /// Create new session ...
else { for mut item in self.items.iter_mut() { if item.scheme() == url.scheme() { return item.open(url, flags); } } None } } }
{ let mut list = String::new(); for item in self.items.iter() { let scheme = item.scheme(); if !scheme.is_empty() { if !list.is_empty() { list = list + "\n" + scheme; } else { ...
conditional_block
issue-9446.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 ...
(String); impl Wrapper { pub fn new(wrapped: String) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complai...
Wrapper
identifier_name
issue-9446.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_string()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-b...
let Wrapper(ref s) = *self; println!("hello {}", *s); } }
random_line_split
issue-9446.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_string()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-box ty Wrapper::new("Bob".to_string()).say...
{}
identifier_body
htmlhrelement.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 crate::dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods}; use crate::dom::b...
} impl HTMLHRElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLHRElement { HTMLHRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] ...
pub struct HTMLHRElement { htmlelement: HTMLElement,
random_line_split
htmlhrelement.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 crate::dom::bindings::codegen::Bindings::HTMLHRElementBinding::{self, HTMLHRElementMethods}; use crate::dom::b...
(&self) -> LengthOrPercentageOrAuto { unsafe { (&*self.upcast::<Element>().unsafe_get()) .get_attr_for_layout(&ns!(), &local_name!("width")) .map(AttrValue::as_dimension) .cloned() .unwrap_or(LengthOrPercentageOrAuto::Auto) } } ...
get_width
identifier_name
extern-call-scrub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
});
random_line_split
extern-call-scrub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { count(data - 1) + count(data - 1) } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) let...
{ data }
conditional_block
extern-call-scrub.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 ...
(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) let _t = Thread::spawn(move|| { let result = count(12); ...
count
identifier_name
extern-call-scrub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn count(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) let _t = Thread::spawn(move|| { let result = count(1...
{ if data == 1 { data } else { count(data - 1) + count(data - 1) } }
identifier_body
background.rs
use super::SkewTContext; use crate::{ app::config::{self}, coords::TPCoords, gui::DrawingArgs, }; use metfor::{Celsius, CelsiusDiff, HectoPascal, Quantity}; impl SkewTContext { pub fn draw_clear_background(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow())...
} }
} cr.close_path(); cr.fill().unwrap();
random_line_split
background.rs
use super::SkewTContext; use crate::{ app::config::{self}, coords::TPCoords, gui::DrawingArgs, }; use metfor::{Celsius, CelsiusDiff, HectoPascal, Quantity}; impl SkewTContext { pub fn draw_clear_background(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow())...
fn draw_temperature_band(&self, cold_t: Celsius, warm_t: Celsius, args: DrawingArgs<'_, '_>) { let cr = args.cr; // Assume color has already been set up for us. const MAXP: HectoPascal = config::MAXP; const MINP: HectoPascal = config::MINP; let mut coords = [ ...
{ let (cr, config) = (args.cr, args.ac.config.borrow()); let rgba = config.dendritic_zone_rgba; cr.set_source_rgba(rgba.0, rgba.1, rgba.2, rgba.3); self.draw_temperature_band(Celsius(-18.0), Celsius(-12.0), args); }
identifier_body
background.rs
use super::SkewTContext; use crate::{ app::config::{self}, coords::TPCoords, gui::DrawingArgs, }; use metfor::{Celsius, CelsiusDiff, HectoPascal, Quantity}; impl SkewTContext { pub fn draw_clear_background(&self, args: DrawingArgs<'_, '_>) { let (cr, config) = (args.cr, args.ac.config.borrow())...
(&self, cold_t: Celsius, warm_t: Celsius, args: DrawingArgs<'_, '_>) { let cr = args.cr; // Assume color has already been set up for us. const MAXP: HectoPascal = config::MAXP; const MINP: HectoPascal = config::MINP; let mut coords = [ (warm_t.unpack(), MAXP.unpack...
draw_temperature_band
identifier_name
asm.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...
(&self) -> State { match *self { Asm => Outputs, Outputs => Inputs, Inputs => Clobbers, Clobbers => Options, Options => StateNone, StateNone => StateNone } } } static OPTIONS: &'static [&'static str] = &["volatile...
next
identifier_name
asm.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...
let span = p.last_span; p.expect(&token::OpenDelim(token::Paren)); let out = p.parse_expr(); p.expect(&token::CloseDelim(token::Paren)); // Expands a read+write operand into two operands. // ...
let (constraint, _str_style) = p.parse_str();
random_line_split
asm.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...
} static OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"]; pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let mut p = cx.new_parser_from_tts(tts); let mut asm = InternedString::new(""); let mut asm...
{ match *self { Asm => Outputs, Outputs => Inputs, Inputs => Clobbers, Clobbers => Options, Options => StateNone, StateNone => StateNone } }
identifier_body
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub e...
(err: net::AddrParseError) -> Self { Error::NetParseError(err) } } impl From<native_tls::Error> for Error { fn from(error: native_tls::Error) -> Self { Error::NativeTls(error) } }
from
identifier_name
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub e...
} impl From<net::AddrParseError> for Error { fn from(err: net::AddrParseError) -> Self { Error::NetParseError(err) } } impl From<native_tls::Error> for Error { fn from(error: native_tls::Error) -> Self { Error::NativeTls(error) } }
fn from(err: toml::ser::Error) -> Self { Error::TomlSerializeError(err) }
random_line_split
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub e...
Error::OfflinePackageNotFound(ref ident) => { format!("No installed package or cached artifact could be found locally in \ offline mode: {}", ident) } Error::PackageNotFound(ref e) => format!("Package not found. {}", e...
{ format!("Cached origin key not found in offline mode: {}", name_with_rev) }
conditional_block
error.rs
use std::{env, error, fmt, io, net, path::PathBuf, result, str, string}; use crate::{api_client, hcore::{self, package::PackageIdent}}; pub type Result<T> = result::Result<T, Error>; #[derive(Debug)] pub e...
} impl From<env::JoinPathsError> for Error { fn from(err: env::JoinPathsError) -> Self { Error::JoinPathsError(err) } } impl From<str::Utf8Error> for Error { fn from(err: str::Utf8Error) -> Self { Error::StrFromUtf8Error(err) } } impl From<string::FromUtf8Error> for Error { fn from(err: string::FromUtf8...
{ Error::IO(err) }
identifier_body
read_spec.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 lig::read::{read, read_attribute, read_entity, read_value}; use lig::*; use ligature::{Attribute, Entity, Stateme...
fn read_attributes() -> Result<(), LigError> { let a = "@<test>"; assert_eq!(read_attribute(a)?, Attribute::new("test")?); Ok(()) } #[test] fn read_string_literals() -> Result<(), LigError> { let s = "\"test\""; assert_eq!(read_value(s)?, Value::StringLiteral("test".to_string())); Ok(()) } #[t...
); } #[test]
random_line_split
read_spec.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 lig::read::{read, read_attribute, read_entity, read_value}; use lig::*; use ligature::{Attribute, Entity, Stateme...
#[test] fn read_attributes() -> Result<(), LigError> { let a = "@<test>"; assert_eq!(read_attribute(a)?, Attribute::new("test")?); Ok(()) } #[test] fn read_string_literals() -> Result<(), LigError> { let s = "\"test\""; assert_eq!(read_value(s)?, Value::StringLiteral("test".to_string())); Ok(...
{ let e = "<test>"; assert_eq!( read_entity(e), Entity::new("test").map_err(|_| LigError("Could not create entity.".into())) ); }
identifier_body
read_spec.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 lig::read::{read, read_attribute, read_entity, read_value}; use lig::*; use ligature::{Attribute, Entity, Stateme...
() -> Result<(), LigError> { let f = "1.2"; assert_eq!(read_value(f)?, Value::FloatLiteral(1.2)); Ok(()) } #[test] fn read_byte_arrays_literals() -> Result<(), LigError> { let b = "0x00ff"; assert_eq!(read_value(b)?, Value::BytesLiteral(vec![0, 255])); Ok(()) } #[test] fn read_entity_as_value(...
read_float_literals
identifier_name
input.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 script_traits::MouseButton; use std::path::Path; use std::mem::size_of; use std::mem::transmute; use std::mem...
else { touch_count += 1; } } slots[current_slot].tracking_id = event.value; }, (EV_ABS, _) => println!("Unknown ABS code {}", event.code), (_, _) => println!("Unknown event type {...
{ touch_count -= 1; }
conditional_block
input.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 script_traits::MouseButton; use std::path::Path; use std::mem::size_of; use std::mem::transmute; use std::mem...
(device_path: &Path, sender: &Sender<WindowEvent>) { let mut device = match File::open(device_path) { Ok(dev) => dev, Err(e) => { println!("Couldn't open device! {}", e); return; }, }; let fd = device.as_raw_fd(); let mut x_info: linu...
read_input_device
identifier_name
input.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 script_traits::MouseButton; use std::path::Path; use std::mem::size_of; use std::mem::transmute; use std::mem...
println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno()); } } unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info); if ret < 0 { println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno()); } } let touchWid...
unsafe { let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info); if ret < 0 {
random_line_split
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
use servo_util::str::DOMString; #[deriving(Encodable)] #[must_root] pub struct HTMLFrameElement { pub htmlelement: HTMLElement } impl HTMLFrameElementDerived for EventTarget { fn is_htmlframeelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId)) } } i...
use dom::document::Document; use dom::element::HTMLFrameElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId};
random_line_split
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
}
{ self.htmlelement.reflector() }
identifier_body
htmlframeelement.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::HTMLFrameElementBinding; use dom::bindings::codegen::InheritTypes::HTMLFrame...
(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLFrameElement> { let element = HTMLFrameElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap) } } impl Reflectable for HTMLFrameElement { fn reflector<'a>(&'a self) ...
new
identifier_name
mod.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...
(&mut self, addr: rtio::SocketAddr) -> IoResult<Box<rtio::RtioUdpSocket + Send>> { net::UdpSocket::bind(addr).map(|u| { box u as Box<rtio::RtioUdpSocket + Send> }) } fn unix_bind(&mut self, path: &CString) -> IoResult<Box<rtio::RtioUnixListener + Send...
udp_bind
identifier_name
mod.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...
n => return n, } } } fn keep_going(data: &[u8], f: |*const u8, uint| -> i64) -> i64 { let origamt = data.len(); let mut data = data.as_ptr(); let mut amt = origamt; while amt > 0 { let ret = retry(|| f(data, amt) as libc::c_int); if ret == 0 { break ...
{}
conditional_block
mod.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...
#[cfg(unix)] #[path = "file_unix.rs"] pub mod file; #[cfg(windows)] #[path = "file_windows.rs"] pub mod file; #[cfg(target_os = "macos")] #[cfg(target_os = "ios")] #[cfg(target_os = "freebsd")] #[cfg(target_os = "dragonfly")] #[cfg(target_os = "android")] #[cfg(target_os = "linux")] #[path = "timer_unix.rs"] pub mod ...
pub mod process; mod util;
random_line_split
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = op...
pub fn print_available_binaries(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_bin, ws, options, "--bin", "binaries") } pub fn print_available_benches(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_b...
{ print_available_targets(Target::is_example, ws, options, "--example", "examples") }
identifier_body
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = op...
( filter_fn: fn(&Target) -> bool, ws: &Workspace<'_>, options: &CompileOptions, option_name: &str, plural_name: &str, ) -> CargoResult<()> { let targets = get_available_targets(filter_fn, ws, options)?; let mut output = String::new(); writeln!(output, "\"{}\" takes one argument.", optio...
print_available_targets
identifier_name
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = op...
bail!("{}", output) } pub fn print_available_examples(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { print_available_targets(Target::is_example, ws, options, "--example", "examples") } pub fn print_available_binaries(ws: &Workspace<'_>, options: &CompileOptions) -> CargoResult<()> { p...
{ writeln!(output, "Possible packages/workspace members:")?; for package in packages { writeln!(output, " {}", package)?; } }
conditional_block
workspace.rs
use crate::core::{Target, Workspace}; use crate::ops::CompileOptions; use crate::util::CargoResult; use anyhow::bail; use std::fmt::Write; fn get_available_targets<'a>( filter_fn: fn(&Target) -> bool, ws: &'a Workspace<'_>, options: &'a CompileOptions, ) -> CargoResult<Vec<&'a str>> { let packages = op...
which can be any package ID specifier in the dependency graph.\n\ Run `cargo help pkgid` for more information about SPEC format.\n\n" .to_string(); if packages.is_empty() { // This would never happen. // Just in case something regresses we covers it here. writeln!(out...
.members() .map(|pkg| pkg.name().as_str()) .collect::<Vec<_>>(); let mut output = "\"--package <SPEC>\" requires a SPEC format value, \
random_line_split
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn
(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAINT_SPEC>) -> Self { R(reader) } } #[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"] pub struct INEPINT_R(crate::FieldReader<u16, u16>); impl INEPINT_R...
deref
identifier_name
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAI...
} impl core::ops::Deref for OUTEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"] #[inline(always)] pub fn in_ep_int(&self) -> INEPINT_R { INEPINT_R...
{ OUTEPINT_R(crate::FieldReader::new(bits)) }
identifier_body
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAI...
pub struct DAINT_SPEC; impl crate::RegisterSpec for DAINT_SPEC { type Ux = u32; } #[doc = "`read()` method returns [daint::R](R) reader structure"] impl crate::Readable for DAINT_SPEC { type Reader = R; } #[doc = "`reset()` method sets DAINT to value 0"] impl crate::Resettable for DAINT_SPEC { #[inline(alwa...
} #[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"]
random_line_split
htmlhrelement.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::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
}
{ let element = HTMLHRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap) }
identifier_body
htmlhrelement.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::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement { HTMLHRElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMStrin...
new_inherited
identifier_name
htmlhrelement.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::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHRElement> { let element = HTMLHRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHRElementBi...
htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
/// Covert non-canonical pseudo-element to canonical one, and keep a /// canonical one as it is. pub fn canonical(&self) -> PseudoElement { match *self { PseudoElement::MozPlaceholder => PseudoElement::Placeholder, _ => self.clone(), } } /// Property flag t...
{ self.is_anon_box() }
identifier_body
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
}
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
(&self) -> Option<PropertyFlags> { match *self { PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER), PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE), PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER), ...
property_restriction
identifier_name
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
wtr.write_all(&header)?; } wtr.write_all(b"\t")?; wtr.write_all(&*util::condense( Cow::Borrowed(&*field), args.flag_condense))?; wtr.write_all(b"\n")?; } } wtr.flush()?; Ok(()) }
{ let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = TabWriter::new(io::stdout()); ...
identifier_body
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
-d, --delimiter <arg> The field delimiter for reading CSV data. Must be a single character. (default:,) "; #[derive(RustcDecodable)] struct Args { arg_input: Option<String>, flag_condense: Option<usize>, flag_separator: String, flag_no_headers: bool, flag_delimiter: ...
Common options: -h, --help Display this message -n, --no-headers When set, the first row will not be interpreted as headers. When set, the name of each field will be its index.
random_line_split
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
wtr.write_all(b"\t")?; wtr.write_all(&*util::condense( Cow::Borrowed(&*field), args.flag_condense))?; wtr.write_all(b"\n")?; } } wtr.flush()?; Ok(()) }
{ wtr.write_all(&header)?; }
conditional_block
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
(argv: &[&str]) -> CliResult<()> { let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = Tab...
run
identifier_name
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
}
{ sources.difference(paths).collect() }
identifier_body
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
() { let unsorted = vec![1, 3, 2]; check_sorted(&unsorted); } #[cfg(test)] mod tests { use regex::Regex; use std::collections::HashSet; use std::io::{BufReader, BufRead}; use std::fs::{self, File}; use std::path::Path; /// A test to check if all source files are covered by `Cargo.toml...
test_check_unsorted
identifier_name
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
} /// Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::read_dir("./src").unwrap(); paths.map(|p| { p.unwrap() .path() .file_name() .unwrap() ...
{ println!("Error, the following source files are not covered by Cargo.toml:"); for source in &not_covered { println!("{}", source); } panic!("Please add the previous source files to Cargo.toml"); }
conditional_block
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
/// Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open("./Cargo.toml").unwrap(); let reader = BufReader::new(c_toml); let regex = Regex::new("path = \"(.*)\"").unwrap(); reader.lines() .filter...
}
random_line_split
expr-match-generic-unique1.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 ...
<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = match true { true => { expected.clone() }, _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *...
test_generic
identifier_name
expr-match-generic-unique1.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 ...
, _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); } pub fn main() { test_box(); }
{ expected.clone() }
conditional_block
expr-match-generic-unique1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { test_box(); }
{ fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); }
identifier_body
expr-match-generic-unique1.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 ...
assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); } pub fn main() { test_box(); }
_ => panic!("wat") };
random_line_split
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::ti...
() { // start sdl2 with everything let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut lag = 0; let mut last_tick: DateTime<UTC> = UTC::now(); let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap(); // Create a window let window = match video_ct...
main
identifier_name
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::ti...
let mut events = ctx.event_pump().unwrap(); let mut game = Game::new(); let mut visualizer = Visualizer::new(renderer); // loop until we receive a QuitEvent 'event : loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, ...
{ // start sdl2 with everything let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut lag = 0; let mut last_tick: DateTime<UTC> = UTC::now(); let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap(); // Create a window let window = match video_ctx.w...
identifier_body
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::ti...
let mut visualizer = Visualizer::new(renderer); // loop until we receive a QuitEvent 'event : loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, _ => game.proc_event(event), } } ...
random_line_split
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
(mut cx: FunctionContext) -> JsResult<JsNumber> { let n = cx.len(); Ok(cx.number(n)) } pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.this().upcast()) } pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> { let this = cx.this(); let this = this.do...
num_arguments
identifier_name
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
{ let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber>() { Ok(cx.string(format!("{}", e))) } else { panic!() } }
identifier_body
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = cx.number(0); for _ in 1..100 { i = cx.compute_scoped(|mut cx| { let n = cx.number(1); Ok(cx.number((i.value() as i32) + (n.value() as i32))) })?; } Ok(i) } pub fn throw_and_catch...
Ok(cx.number(i)) }
random_line_split
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
else { panic!() } }
{ Ok(cx.string(format!("{}", e))) }
conditional_block
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { ...
let year = year.unwrap(); let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id); let data = WorksheetModel { year: year, has_activities: activities.len() > 0, activities: activities.iter().map(|a| ActivityModel { ...
{ res.set(StatusCode::BadRequest); return res.send("Invalid year"); }
conditional_block
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { ...
} #[derive(RustcEncodable)] struct WorksheetModel { year: i32, has_activities: bool, activities: Vec<ActivityModel> } #[derive(RustcEncodable)] struct ActivityModel { points: i32, description: String }
random_line_split
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { ...
{ points: i32, description: String }
ActivityModel
identifier_name
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> Prim...
let mut common = Vec::new(); if (all_factors.len() == 0) { return common; } let mut first = 0; let highest = all_factors[all_factors.len() - 1]; for comp in all_factors { if comp > 255 { return common; } let mut lowest_index = 0; let mut lowest = highest; let mut freq = 0; let mut have_remain...
let mut progress = vec![0; factors.len() as usize];
random_line_split
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> Prim...
(factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> { let all_factors = maximum_factors(factors); let mut progress = vec![0; factors.len() as usize]; let mut common = Vec::new(); if (all_factors.len() == 0) { return common; } let mut first = 0; let highest = all_factors[all_factors.len() - 1]; ...
high_freq_factors
identifier_name
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> Prim...
} pub fn isqrt(number: u64) -> u64 { return (number as f64).sqrt().ceil() as u64; } pub fn factors(number: u64) -> Vec<u64> { let mut result = vec![]; let mut remain = number; let mut i = 2; while (i <= remain) { if remain % i == 0 { remain /= i; result.push(i); } else { i += 1; } } retur...
{ return match self.values.binary_search(elem) { Ok(index) => Some(index), Err(_) => None, } }
identifier_body
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
() -> V2DeflateSerializer { V2DeflateSerializer { uncompressed_buf: Vec::new(), compressed_buf: Vec::new(), v2_serializer: V2Serializer::new(), } } } impl Serializer for V2DeflateSerializer { type SerializeError = V2DeflateSerializeError; fn serialize<T:...
new
identifier_name
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
} impl fmt::Display for V2DeflateSerializeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { V2DeflateSerializeError::InternalSerializationError(e) => { write!(f, "The underlying serialization failed: {}", e) } V2DeflateSerialize...
{ V2DeflateSerializeError::IoError(e) }
identifier_body
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
// TODO pluggable compressors? configurable compression levels? // TODO benchmark https://github.com/sile/libflate // TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the // data instead of shrinking it (which we cannot really predict), writing to compres...
.write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?; // placeholder for length self.compressed_buf.write_u32::<BigEndian>(0)?;
random_line_split
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
} } } impl error::Error for V2DeflateSerializeError { fn source(&self) -> Option<&(dyn error::Error +'static)> { match self { V2DeflateSerializeError::InternalSerializationError(e) => Some(e), V2DeflateSerializeError::IoError(e) => Some(e), } } } /// Serial...
{ write!(f, "The underlying serialization failed: {}", e) }
conditional_block
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1...
main
identifier_name
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } ...
random_line_split
linear-for-loop.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 ...
assert_eq!(i, 11); }
{ let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { ...
identifier_body
linear-for-loop.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 ...
if i == 4 { assert!((c == 'o' as u8)); } //... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
{ assert!((c == 'l' as u8)); }
conditional_block
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test() { let mutex = RMutex::new(0i32); { let mut outer_lock = mutex.lock(); { l...
() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guards = Vec::new(); for _ in (0..count) { let mutex = mutex.clone(); guards.push(Thread::scoped(move || { let mut value_ref = mutex.lock(); let value = *value_ref; sleep(Duratio...
test_guarding
identifier_name
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test() { let mutex = RMutex::new(0i32);
let mut outer_lock = mutex.lock(); { let mut inner_lock = mutex.lock(); *inner_lock = 1; } *outer_lock = 2; } assert_eq!(*mutex.lock(), 2); } #[test] fn test_guarding() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guard...
{
random_line_split
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test()
#[test] fn test_guarding() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guards = Vec::new(); for _ in (0..count) { let mutex = mutex.clone(); guards.push(Thread::scoped(move || { let mut value_ref = mutex.lock(); let value = *value_ref; ...
{ let mutex = RMutex::new(0i32); { let mut outer_lock = mutex.lock(); { let mut inner_lock = mutex.lock(); *inner_lock = 1; } *outer_lock = 2; } assert_eq!(*mutex.lock(), 2); }
identifier_body
no_0215_kth_largest_element_in_an_array.rs
struct Solution; use std::cmp::Ordering; impl Solution { // by zhangyuchen. pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { Self::find(&mut nums, k as usize) } fn find(nums: &mut [i32], k: usize) -> i32 { let mut pos = 1; // 第一个大于等于哨兵的位置 let sentinel = nums[0]; //...
identifier_name
no_0215_kth_largest_element_in_an_array.rs
struct Solution; use std::cmp::Ordering; impl Solution { // by zhangyuchen. pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 { Self::find(&mut nums, k as usize) } fn find(nums: &mut [i32], k: usize) -> i32 {
// 小于哨兵的放到哨兵左侧 let temp = nums[pos]; nums[pos] = nums[i]; nums[i] = temp; pos += 1; } } // 把哨兵放到它应该在的位置, pos-1 是最靠右的小于哨兵的位置 let temp = nums[pos - 1]; nums[pos - 1] = sentinel; nums[0] = te...
let mut pos = 1; // 第一个大于等于哨兵的位置 let sentinel = nums[0]; // 哨兵 for i in 1..nums.len() { if nums[i] < sentinel {
random_line_split
text_view.rs
use std::ops::Deref; use std::sync::Arc; use std::sync::{Mutex, MutexGuard}; use owning_ref::{ArcRef, OwningHandle}; use unicode_width::UnicodeWidthStr; use crate::align::*; use crate::theme::Effect; use crate::utils::lines::spans::{LinesIterator, Row}; use crate::utils::markup::StyledString; use crate::view::{SizeCa...
/// Sets the alignment for this view. pub fn align(mut self, a: Align) -> Self { self.align = a; self } /// Center the text horizontally and vertically inside the view. pub fn center(mut self) -> Self { self.align = Align::center(); self } /// Replace the...
{ self.align.v = v; self }
identifier_body
text_view.rs
use std::ops::Deref; use std::sync::Arc; use std::sync::{Mutex, MutexGuard}; use owning_ref::{ArcRef, OwningHandle}; use unicode_width::UnicodeWidthStr; use crate::align::*; use crate::theme::Effect; use crate::utils::lines::spans::{LinesIterator, Row}; use crate::utils::markup::StyledString; use crate::view::{SizeCa...
(self) -> Self { self.with(|s| s.set_content_wrap(false)) } /// Controls content wrap for this view. /// /// If `true` (the default), text will wrap long lines when needed. pub fn set_content_wrap(&mut self, wrap: bool) { self.wrap = wrap; } /// Sets the horizontal alignmen...
no_wrap
identifier_name
text_view.rs
use std::ops::Deref; use std::sync::Arc; use std::sync::{Mutex, MutexGuard}; use owning_ref::{ArcRef, OwningHandle}; use unicode_width::UnicodeWidthStr; use crate::align::*; use crate::theme::Effect; use crate::utils::lines::spans::{LinesIterator, Row}; use crate::utils::markup::StyledString; use crate::view::{SizeCa...
>, // We also need to keep a copy of Arc so `deref` can return // a reference to the `StyledString` data: Arc<StyledString>, } impl Deref for TextContentRef { type Target = StyledString; fn deref(&self) -> &StyledString { self.data.as_ref() } } impl TextContent { /// Replaces ...
ArcRef<Mutex<TextContentInner>>, MutexGuard<'static, TextContentInner>,
random_line_split
regions-fn-subtyping-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn has_same_region(f: &fn<'a>(x: &'a int, g: &fn(y: &'a int))) { // `f` should be the type that `wants_same_region` wants, but // right now the compiler complains that it isn't. wants_same_region(f); } fn wants_same_region(_f: &fn<'b>(x: &'b int, g: &fn(y: &'b int))) { } pub fn main() { }
random_line_split
regions-fn-subtyping-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { }
main
identifier_name
regions-fn-subtyping-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { }
{ }
identifier_body
types.rs
use game::{Position, Move, Score, NumPlies, NumMoves}; #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)] pub struct NumNodes(pub u64); #[derive(Clone, Debug)] pub struct State { pub pos: Position, pub prev_pos: Option<Position>, pub prev_move: Option<Move>, pub param: Param, } #[derive(C...
}
{ InnerData { nodes: NumNodes(self.nodes.0 + 1) } }
identifier_body
types.rs
use game::{Position, Move, Score, NumPlies, NumMoves}; #[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Debug)] pub struct NumNodes(pub u64); #[derive(Clone, Debug)] pub struct State { pub pos: Position, pub prev_pos: Option<Position>, pub prev_move: Option<Move>, pub param: Param, } #[derive(C...
(pub Move, pub Option<Move>); #[derive(Clone, Debug)] pub struct Report { pub data: Data, pub score: Score, pub pv: Vec<Move>, } #[derive(Clone, Debug)] pub struct Data { pub nodes: NumNodes, pub depth: NumPlies, } // TODO put actual data here #[derive(Clone, Debug)] pub struct InnerData { pu...
BestMove
identifier_name