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 |
|---|---|---|---|---|
htmliframeelement.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::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom:... |
pub fn Name(&self) -> DOMString {
~""
}
pub fn SetName(&mut self, _name: DOMString) -> ErrorResult {
Ok(())
}
pub fn Sandbox(&self, _abstract_self: AbstractNode) -> DOMString {
match self.htmlelement.element.GetAttribute(~"sandbox") {
Some(s) => s.to_owned(),
... | {
Ok(())
} | identifier_body |
htmliframeelement.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::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom:... | use dom::windowproxy::WindowProxy;
use extra::url::Url;
use servo_msg::constellation_msg::{PipelineId, SubpageId};
use std::ascii::StrAsciiExt;
enum SandboxAllowance {
AllowNothing = 0x00,
AllowSameOrigin = 0x01,
AllowTopNavigation = 0x02,
AllowForms = 0x04,
AllowScripts = 0x08,
AllowPointerLo... | random_line_split | |
htmliframeelement.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::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom:... | (&self) -> DOMString {
~""
}
pub fn SetLongDesc(&mut self, _longdesc: DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginHeight(&self) -> DOMString {
~""
}
pub fn SetMarginHeight(&mut self, _marginheight: DOMString) -> ErrorResult {
Ok(())
}
pub fn Marg... | LongDesc | identifier_name |
parse.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 cg;
use quote::Tokens;
use syn::DeriveInput;
use synstructure;
use to_css::CssVariantAttrs;
pub fn derive(inp... | }
/// Parse this keyword from a string slice.
#[inline]
pub fn from_ident(ident: &str) -> Result<Self, ()> {
match_ignore_ascii_case! { ident,
#match_body
_ => Err(()),
}
}
}
... | random_line_split | |
parse.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 cg;
use quote::Tokens;
use syn::DeriveInput;
use synstructure;
use to_css::CssVariantAttrs;
pub fn | (input: DeriveInput) -> Tokens {
let name = &input.ident;
let mut match_body = quote! {};
let style = synstructure::BindStyle::Ref.into();
synstructure::each_variant(&input, &style, |bindings, variant| {
assert!(
bindings.is_empty(),
"Parse is only supported for single-... | derive | identifier_name |
parse.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 cg;
use quote::Tokens;
use syn::DeriveInput;
use synstructure;
use to_css::CssVariantAttrs;
pub fn derive(inp... | #identifier => Ok(#name::#ident),
};
let aliases = match variant_attrs.aliases {
Some(aliases) => aliases,
None => return,
};
for alias in aliases.split(",") {
match_body = quote! {
#match_body
#alias => Ok... | {
let name = &input.ident;
let mut match_body = quote! {};
let style = synstructure::BindStyle::Ref.into();
synstructure::each_variant(&input, &style, |bindings, variant| {
assert!(
bindings.is_empty(),
"Parse is only supported for single-variant enums for now"
... | identifier_body |
main.rs | use PlanetaryMonster::MarsMonster;
enum Compass {
North, South, East, West | VenusMonster(species, i32),
MarsMonster(species, i32)
}
fn main() {
let direction = Compass::West;
let martian = PlanetaryMonster::MarsMonster("Chela", 42);
let martian = MarsMonster("Chela", 42);
// using enum values:
// error: binary operation `==` cannot be applied to type `Compass`
// if direction == Comp... | }
type species = &'static str;
enum PlanetaryMonster { | random_line_split |
main.rs | use PlanetaryMonster::MarsMonster;
enum Compass {
North, South, East, West
}
type species = &'static str;
enum PlanetaryMonster {
VenusMonster(species, i32),
MarsMonster(species, i32)
}
fn | () {
let direction = Compass::West;
let martian = PlanetaryMonster::MarsMonster("Chela", 42);
let martian = MarsMonster("Chela", 42);
// using enum values:
// error: binary operation `==` cannot be applied to type `Compass`
// if direction == Compass::East {
// println!("Go to the east");
// }
match direct... | main | identifier_name |
parsing_quirks_test.rs | #[test]
fn test_parsing_css() {
let text = " div { font-weight: bold; } ";
assert_template_result!(text, text);
}
#[test]
fn test_raise_on_single_close_bracet() {
assert_parse_error!("text {{method} oh nos!");
}
#[test]
fn test_raise_on_label_and_no_close_bracets() {
assert_parse_error!("TEST {{ ");
}... | () {
assert_parse_error!("TEST {% ");
}
#[test]
fn test_error_on_empty_filter() {
// Implementation specific: lax parser
assert_parse_error!("{{|test}}");
assert_parse_error!("{{test |a|b|}}");
}
#[test]
fn test_meaningless_parens_error() {
assert_parse_error!(
"{% if a == 'foo' or (b == ... | test_raise_on_label_and_no_close_bracets_percent | identifier_name |
parsing_quirks_test.rs | #[test]
fn test_parsing_css() {
let text = " div { font-weight: bold; } ";
assert_template_result!(text, text);
}
#[test]
fn test_raise_on_single_close_bracet() {
assert_parse_error!("text {{method} oh nos!");
}
#[test]
fn test_raise_on_label_and_no_close_bracets() {
assert_parse_error!("TEST {{ ");
}... |
#[test]
fn test_meaningless_parens_error() {
assert_parse_error!(
"{% if a == 'foo' or (b == 'bar' and c == 'baz') or false %} YES {% endif %}",
);
}
#[test]
fn test_unexpected_characters_syntax_error() {
assert_parse_error!("{% if true && false %} YES {% endif %}");
assert_parse_error!("{% i... | {
// Implementation specific: lax parser
assert_parse_error!("{{|test}}");
assert_parse_error!("{{test |a|b|}}");
} | identifier_body |
parsing_quirks_test.rs | #[test]
fn test_parsing_css() {
let text = " div { font-weight: bold; } ";
assert_template_result!(text, text);
}
#[test]
fn test_raise_on_single_close_bracet() {
assert_parse_error!("text {{method} oh nos!");
}
#[test]
fn test_raise_on_label_and_no_close_bracets() {
assert_parse_error!("TEST {{ ");
}... | #[test]
#[should_panic]
fn test_unanchored_filter_arguments() {
panic!("Implementation specific: lax parser");
}
#[test]
#[should_panic]
fn test_invalid_variables_work() {
panic!("Implementation specific: lax parser");
}
#[test]
#[should_panic]
fn test_extra_dots_in_ranges() {
panic!("Implementation speci... | #[test]
fn test_raise_on_invalid_tag_delimiter() {
assert_parse_error!("{% end %}");
}
| random_line_split |
util.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of condit... | // Cannot be delete
0x7f => false,
_ => true
}
}
pub fn get_chr_escaped(c: u8) -> String {
match c {
0x20...0x21 | 0x23...0x5b | 0x5D...0x7e => (c as char).to_string(),
_ => format!("\\u00{:02x}", c),
}
}
pub struct Latin1Str<'a> {
bytes: &'a [u8],
}
impl<'a> Lat... | 0...0x9f => false,
| identifier_name |
util.rs | /*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of condit... |
pub fn debug_escaped_name(&self) -> String {
let mut ret = String::new();
for c in self.bytes {
ret += &get_chr_escaped(*c);
}
ret
}
pub fn valid_for_basic_id(&self) -> bool {
// Needs to be at least one character long
if self.bytes.len() == 0 {
... | utf8str
} | random_line_split |
buffer.rs | use std::ptr;
use std::io::Read;
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buf... | &self.buffer[..$size]
}
fn current_buffer(&self) -> &[u8] {
&self.buffer[..self.position]
}
fn position(&self) -> usize { self.position }
fn remaining(&self) -> usize { $size - self.position }
fn size() -> usize ... | fn full_buffer(&mut self) -> &[u8] {
assert!(self.position == $size);
self.position = 0; | random_line_split |
buffer.rs | use std::ptr;
use std::io::Read;
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buf... | (dst: &mut [u8]) {
unsafe {
ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len());
}
}
| zero | identifier_name |
buffer.rs | use std::ptr;
use std::io::Read;
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buf... | {
unsafe {
ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len());
}
} | identifier_body | |
buffer.rs | use std::ptr;
use std::io::Read;
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buf... |
self.zero_until(size - rem);
}
}
/// Zero all bytes in dst
#[inline]
pub fn zero(dst: &mut [u8]) {
unsafe {
ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len());
}
}
| {
self.zero_until(size);
func(self.full_buffer());
} | conditional_block |
http.rs |
use url::Url;
use url::ParseError as UrlError;
use method;
use status::StatusCode;
use uri;
use uri::RequestUri::{AbsolutePath, AbsoluteUri, Authority, Star};
use version::HttpVersion;
use version::HttpVersion::{Http09, Http10, Http11, Http20};
use HttpError::{HttpHeaderError, HttpIoError, HttpMethodError, HttpStatus... | use std::num::from_u16;
use std::str::{self, FromStr};
use std::string::CowString; | random_line_split | |
http.rs | n();
debug!("chunked write, size = {:?}", chunk_size);
try!(write!(w, "{:X}{}", chunk_size, LINE_ENDING));
try!(w.write_all(msg));
w.write_str(LINE_ENDING)
},
SizedWriter(ref mut w, ref mut remaining) => {
let len = ... | test_write_chunked | identifier_name | |
http.rs |
}
impl<R: Reader> Reader for HttpReader<R> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
match *self {
SizedReader(ref mut body, ref mut remaining) => {
debug!("Sized read, remaining={:?}", remaining);
if *remaining == 0 {
Err(old... | {
match self {
SizedReader(r, _) => r,
ChunkedReader(r, _) => r,
EofReader(r) => r,
EmptyReader(r) => r,
}
} | identifier_body | |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use dom::bindings::cell::DomRefCell... | (
global: &GlobalScope,
url: USVString,
status: u16,
) -> Fallible<DomRoot<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
// Step 2
let url = match parsed_url {
Ok(url) => url,
... | Redirect | identifier_name |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use dom::bindings::cell::DomRefCell... | pub fn Error(global: &GlobalScope) -> DomRoot<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
*r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
r
}
// https://fetch.spec.w... |
// https://fetch.spec.whatwg.org/#dom-response-error | random_line_split |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use dom::bindings::cell::DomRefCell... |
// Step 2
if!is_valid_status_text(&init.statusText) {
return Err(Error::Type(
"init's statusText member does not match the reason-phrase token production"
.to_string(),
));
}
// Step 3
let r = Response::new(global);
... | {
return Err(Error::Range(format!(
"init's status member should be in the range 200 to 599, inclusive, but is {}",
init.status
)));
} | conditional_block |
response.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 body::{BodyOperations, BodyType, consume_body, consume_body_with_promise};
use dom::bindings::cell::DomRefCell... |
fn is_locked(&self) -> bool {
self.locked()
}
fn take_body(&self) -> Option<Vec<u8>> {
let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
match body {
NetTraitsResponseBody::Done(bytes) => Some(bytes),
body => {
... | {
assert!(self.body_promise.borrow().is_none());
self.body_used.set(true);
*self.body_promise.borrow_mut() = Some((p.clone(), body_type));
} | identifier_body |
outline.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" /> | additional_methods=[Method("outline_has_nonzero_width", "bool")]) %>
// TODO(pcwalton): `invert`
${helpers.predefined_type("outline-color", "CSSColor", "::cssparser::Color::CurrentColor")}
<%helpers:longhand name="outline-style" need_clone="True">
pub use values::specified::BorderStyle as... | <% from data import Method %>
<% data.new_style_struct("Outline",
inherited=False, | random_line_split |
outline.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Out... |
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue)
}
#[derive(Debug, Clone, PartialEq, HeapSizeOf)]
pub struct SpecifiedValue(pub specified::Length);
pub mod computed_value {
use ... | {
self.0.to_css(dest)
} | identifier_body |
outline.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Out... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue)
}
#[derive(Debug, Clone, PartialEq, HeapS... | to_css | identifier_name |
border.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/. */
// FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth.
use app_units::Au;
use crate::display_list::T... | }
fn side_image_width(
border_image_width: BorderImageSideWidth,
border_width: f32,
total_length: Au,
) -> f32 {
match border_image_width {
GenericBorderImageSideWidth::Length(v) => v.to_used_value(total_length).to_f32_px(),
GenericBorderImageSideWidth::Number(x) => border_width * x,
... | side_image_outset(outset.2, border.bottom),
side_image_outset(outset.3, border.left),
) | random_line_split |
border.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/. */
// FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth.
use app_units::Au;
use crate::display_list::T... | else {
edge_length / required
}
}
let top_factor = scale_factor(radii.top_left.width, radii.top_right.width, size.width);
let bottom_factor = scale_factor(
radii.bottom_left.width,
radii.bottom_right.width,
size.width,
);
let left_factor = scale_factor(r... | {
1.0
} | conditional_block |
border.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/. */
// FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth.
use app_units::Au;
use crate::display_list::T... | (abs_bounds: Rect<Au>, border_style: &Border) -> BorderRadius {
// TODO(cgaebel): Support border radii even in the case of multiple border widths.
// This is an extension of supporting elliptical radii. For now, all percentage
// radii will be relative to the width.
overlapping_radii(
abs_bound... | radii | identifier_name |
border.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/. */
// FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth.
use app_units::Au;
use crate::display_list::T... |
fn side_image_width(
border_image_width: BorderImageSideWidth,
border_width: f32,
total_length: Au,
) -> f32 {
match border_image_width {
GenericBorderImageSideWidth::Length(v) => v.to_used_value(total_length).to_f32_px(),
GenericBorderImageSideWidth::Number(x) => border_width * x,
... | {
SideOffsets2D::new(
side_image_outset(outset.0, border.top),
side_image_outset(outset.1, border.right),
side_image_outset(outset.2, border.bottom),
side_image_outset(outset.3, border.left),
)
} | identifier_body |
mod.rs | pub use self::index_pool::IndexPool;
pub use self::debug_draw::DebugDraw;
pub use self::timer::Timer;
use cgmath::*;
use std::ops::Mul;
use std::f32;
mod index_pool;
mod timer;
pub mod debug_draw;
//
// Global tuning constants based on meters-kilograms-seconds (MKS) units.
//
// Collision
/// The maximum number of... | /// Performs the cross product on a scalar and a vector. In 2D this produces a vector.
pub fn cross_s_v(s: f32, v: &Vector2<f32>) -> Vector2<f32> {
Vector2::<f32> {
x: -s * v.y,
y: s * v.x,
}
}
pub fn clamp_f32(s: f32, low: f32, high: f32) -> f32 {
f32::max(low, f32::min(s, high))
}
#[deri... | random_line_split | |
mod.rs | pub use self::index_pool::IndexPool;
pub use self::debug_draw::DebugDraw;
pub use self::timer::Timer;
use cgmath::*;
use std::ops::Mul;
use std::f32;
mod index_pool;
mod timer;
pub mod debug_draw;
//
// Global tuning constants based on meters-kilograms-seconds (MKS) units.
//
// Collision
/// The maximum number of... | (&self, rhs: &Rotation2d) -> Rotation2d {
// q = self, r = rhs
// [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc]
// [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc]
Rotation2d {
sin: self.cos * rhs.sin - self.sin * rhs.cos,
cos: self.cos * rhs.cos + self.sin * rhs.... | mul_t | identifier_name |
mod.rs | pub use self::index_pool::IndexPool;
pub use self::debug_draw::DebugDraw;
pub use self::timer::Timer;
use cgmath::*;
use std::ops::Mul;
use std::f32;
mod index_pool;
mod timer;
pub mod debug_draw;
//
// Global tuning constants based on meters-kilograms-seconds (MKS) units.
//
// Collision
/// The maximum number of... |
#[derive(Clone, Copy, Debug)]
pub struct Rotation2d {
sin: f32,
cos: f32,
}
impl Default for Rotation2d {
/// Constructs a new identity rotation.
fn default() -> Rotation2d {
Rotation2d {
sin: 0.0,
cos: 1.0,
}
}
}
impl Rotation2d {
/// Constructs a new... | {
f32::max(low, f32::min(s, high))
} | identifier_body |
tup.rs | //! A tuple for pattern matching purposes, until vector pattern matching is enabled in stable.
//!
//! This code is not very pretty at all but it compiles without enabling any experimental features.
#[derive(Debug)]
pub enum Tup<A,B,C,D,E,F,G,H,I> {
T0,
T1(A),
T2(A, B),
T3(A, B, C),
T4(A, B, C, D),... | 5 => Some(Tup::T5(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone())),
6 => Some(Tup::T6(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone(), vec[4].clone(), vec[5].clone())),
7 => Some(Tup::T7(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone()... | 1 => Some(Tup::T1(vec[0].clone())),
2 => Some(Tup::T2(vec[0].clone(), vec[1].clone())),
3 => Some(Tup::T3(vec[0].clone(), vec[1].clone(), vec[2].clone())),
4 => Some(Tup::T4(vec[0].clone(), vec[1].clone(), vec[2].clone(), vec[3].clone())), | random_line_split |
tup.rs | //! A tuple for pattern matching purposes, until vector pattern matching is enabled in stable.
//!
//! This code is not very pretty at all but it compiles without enabling any experimental features.
#[derive(Debug)]
pub enum | <A,B,C,D,E,F,G,H,I> {
T0,
T1(A),
T2(A, B),
T3(A, B, C),
T4(A, B, C, D),
T5(A, B, C, D, E),
T6(A, B, C, D, E, F),
T7(A, B, C, D, E, F, G),
T8(A, B, C, D, E, F, G, H),
T9(A, B, C, D, E, F, G, H, I),
}
pub type TupT<T> = Tup<T,T,T,T,T,T,T,T,T>;
pub fn vec_to_tup<T: Clone>(vec: &Ve... | Tup | identifier_name |
classes.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 ... | (&mut self) {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
}
}
fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
pub fn main() {
le... | meow | identifier_name |
classes.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
impl cat {
fn meow(&mut self) {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
}
}
fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_na... | {
println!("Not hungry!");
return false;
} | conditional_block |
classes.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 cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
pub fn main() {
let mut nyan = cat(0u, 2, "nyan".to_string());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat(... | {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
} | identifier_body |
classes.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 ... | meows: in_x,
how_hungry: in_y,
name: in_name
}
}
pub fn main() {
let mut nyan = cat(0u, 2, "nyan".to_string());
nyan.eat();
assert!((!nyan.eat()));
for _ in range(1u, 10u) { nyan.speak(); };
assert!((nyan.eat()));
} | }
fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat { | random_line_split |
save.rs | #[cfg(test)]
#[path = "./save_tests.rs"]
pub mod save_tests;
use arrayvec::ArrayVec;
use dice::Dice;
pub fn save(
dice: &mut Dice,
save: Option<i32>,
rend: i32,
reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>,
) -> bool {
match save {
Some(save) => {
le... |
},
None => false,
}
}
| {
save_roll >= modified_save
} | conditional_block |
save.rs | #[cfg(test)]
#[path = "./save_tests.rs"]
pub mod save_tests;
use arrayvec::ArrayVec;
use dice::Dice;
pub fn save(
dice: &mut Dice,
save: Option<i32>,
rend: i32,
reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>,
) -> bool {
match save {
Some(save) => { | let save_roll = save_roll;
if save_roll == 1 {
false
} else {
save_roll >= modified_save
}
},
None => false,
}
} | let mut save_roll = dice.roll_d6() as i32;
let modified_save = save - rend;
if reroll_save_triggers.into_iter().any(|trigger| trigger(save_roll, modified_save)) {
save_roll = dice.roll_d6() as i32;
} | random_line_split |
save.rs | #[cfg(test)]
#[path = "./save_tests.rs"]
pub mod save_tests;
use arrayvec::ArrayVec;
use dice::Dice;
pub fn save(
dice: &mut Dice,
save: Option<i32>,
rend: i32,
reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>,
) -> bool | {
match save {
Some(save) => {
let mut save_roll = dice.roll_d6() as i32;
let modified_save = save - rend;
if reroll_save_triggers.into_iter().any(|trigger| trigger(save_roll, modified_save)) {
save_roll = dice.roll_d6() as i32;
}
l... | identifier_body | |
save.rs | #[cfg(test)]
#[path = "./save_tests.rs"]
pub mod save_tests;
use arrayvec::ArrayVec;
use dice::Dice;
pub fn | (
dice: &mut Dice,
save: Option<i32>,
rend: i32,
reroll_save_triggers: ArrayVec<[fn(i32, i32) -> bool; ::MAX_CALLBACKS]>,
) -> bool {
match save {
Some(save) => {
let mut save_roll = dice.roll_d6() as i32;
let modified_save = save - rend;
if reroll_save_tr... | save | identifier_name |
lru_cache.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 ... |
/// Change the number of key-value pairs the cache can hold. Remove
/// least-recently-used key-value pairs if necessary.
pub fn change_capacity(&mut self, capacity: uint) {
for _ in range(capacity, self.len()) {
self.remove_lru();
}
self.max_size = capacity;
}
... | {
self.max_size
} | identifier_body |
lru_cache.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> uint {
self.map.len()
}
}
impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> {
/// Clear the cache of all key-value pairs.
fn clear(&mut self) {
self.map.clear();
}
}
#[unsafe_destructor]
impl<K, V> Drop for LruCache<K, V> {
fn drop(&mut self) {
unsafe {
... | len | identifier_name |
lru_cache.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 ... |
Some(node) => {
let keyref = unsafe { &(*node_ptr).key };
self.map.swap(KeyRef{k: keyref}, node);
self.attach(node_ptr);
if self.len() > self.capacity() {
self.remove_lru();
}
}
}
}
... | {
// Existing node, just update LRU position
self.detach(node_ptr);
self.attach(node_ptr);
} | conditional_block |
lru_cache.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 ... | match node_ptr_opt {
None => (),
Some(node_ptr) => {
self.detach(node_ptr);
self.attach(node_ptr);
}
}
return value;
}
/// Remove and return a value corresponding to the key from the cache.
pub fn pop(&mut self, k: ... | let node_ptr: *mut LruEntry<K, V> = &mut **node;
(Some(unsafe { &(*node_ptr).value }), Some(node_ptr))
}
}; | random_line_split |
027.rs | // Copyright (C) 2014 Jorge Aparicio
extern crate num;
use num::Integer;
use std::iter::{count,range_inclusive};
fn main() {
let limit = 999; | let len = prime_length(a, b);
if len > max {
max = len;
ans = a * b;
}
}
}
println!("{}", ans);
}
fn prime_length(a:int, b: int) -> uint {
count(0u, 1).skip_while(|&n| {
let p = polyval(a, b, n as int);
p > 1 && ... | let (mut ans, mut max) = (0, 0);
for a in range_inclusive(-limit, limit) {
for b in range_inclusive(-limit, limit) { | random_line_split |
027.rs | // Copyright (C) 2014 Jorge Aparicio
extern crate num;
use num::Integer;
use std::iter::{count,range_inclusive};
fn main() {
let limit = 999;
let (mut ans, mut max) = (0, 0);
for a in range_inclusive(-limit, limit) {
for b in range_inclusive(-limit, limit) {
let len = prime_length(a,... | (a:int, b: int) -> uint {
count(0u, 1).skip_while(|&n| {
let p = polyval(a, b, n as int);
p > 1 && is_prime(p as uint)
}).next().unwrap()
}
fn polyval(a: int, b: int, n: int) -> int {
n * n + a * n + b
}
fn is_prime(n: uint) -> bool {
let mut p = 2;
loop {
if p * p > n { ... | prime_length | identifier_name |
027.rs | // Copyright (C) 2014 Jorge Aparicio
extern crate num;
use num::Integer;
use std::iter::{count,range_inclusive};
fn main() |
fn prime_length(a:int, b: int) -> uint {
count(0u, 1).skip_while(|&n| {
let p = polyval(a, b, n as int);
p > 1 && is_prime(p as uint)
}).next().unwrap()
}
fn polyval(a: int, b: int, n: int) -> int {
n * n + a * n + b
}
fn is_prime(n: uint) -> bool {
let mut p = 2;
loop {
... | {
let limit = 999;
let (mut ans, mut max) = (0, 0);
for a in range_inclusive(-limit, limit) {
for b in range_inclusive(-limit, limit) {
let len = prime_length(a, b);
if len > max {
max = len;
ans = a * b;
}
}
}
pr... | identifier_body |
027.rs | // Copyright (C) 2014 Jorge Aparicio
extern crate num;
use num::Integer;
use std::iter::{count,range_inclusive};
fn main() {
let limit = 999;
let (mut ans, mut max) = (0, 0);
for a in range_inclusive(-limit, limit) {
for b in range_inclusive(-limit, limit) {
let len = prime_length(a,... | else { 2 };
}
true
}
| { 1 } | conditional_block |
mod.rs | #![allow(non_camel_case_types)]
pub mod libtsm {
use std::num::{FromPrimitive};
use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char};
use collections::enum_set::{EnumSet,CLike};
static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
#[deriving(PartialEq,Show,Clone,FromPrimitive)]... | (&self, flag: AttributeFlags) -> bool {
self.flags.contains_elem(flag)
}
}
pub struct tsm_screen;
pub struct tsm_vte;
pub struct log_data;
pub struct tsm_vte_write_cb;
pub struct va_list;
pub type tsm_age_t = u32;
pub type tsm_write_cb = extern "C" fn(*const tsm_vte, *const u8, size_t, c_voi... | get_flag | identifier_name |
mod.rs | #![allow(non_camel_case_types)]
pub mod libtsm {
use std::num::{FromPrimitive};
use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char};
use collections::enum_set::{EnumSet,CLike};
static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
#[deriving(PartialEq,Show,Clone,FromPrimitive)]... |
fn from_uint(v: uint) -> AttributeFlags {
FromPrimitive::from_uint(v).expect("Decoding of uint into AttributeFlags failed!")
}
}
impl CLike for ScreenFlags {
fn to_uint(&self) -> uint {
*self as uint
}
fn from_uint(v: uint) -> ScreenFlags {
FromPrimitive::from_uint(v).expect... | {
*self as uint
} | identifier_body |
mod.rs | #![allow(non_camel_case_types)]
pub mod libtsm {
use std::num::{FromPrimitive};
use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char};
use collections::enum_set::{EnumSet,CLike};
static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
#[deriving(PartialEq,Show,Clone,FromPrimitive)]... | pub bb: u8, /* background blue */
pub flags: EnumSet<AttributeFlags>, /* misc flags */
}
fn get_color(code: i8, r: u8, g: u8, b: u8) -> Option<u8> {
if code < 0 {
Some(get_rgb_color(r, g, b))
} else if code >= 0 && code < 16 {
Some(code.to_u8().unwrap())
} else {
None
... | pub fb: u8, /* foreground blue */
pub br: u8, /* background red */
pub bg: u8, /* background green */ | random_line_split |
mod.rs | #![allow(non_camel_case_types)]
pub mod libtsm {
use std::num::{FromPrimitive};
use libc::{c_void, c_uint, c_int, size_t, uint32_t, c_char};
use collections::enum_set::{EnumSet,CLike};
static RGB_LEVELS : &'static [u8] = &[0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff];
#[deriving(PartialEq,Show,Clone,FromPrimitive)]... |
}
fn get_rgb_color(r: u8, g: u8, b: u8) -> u8 {
if r == g && g == b && (r - 8) % 10 == 0 {
return 232 + (r - 8) / 10;
} else {
return 16 + get_rgb_index(r) * 36 + get_rgb_index(g) * 6 + get_rgb_index(b);
}
}
fn get_rgb_index(value: u8) -> u8 {
RGB_LEVELS.iter().position(|level... | {
None
} | conditional_block |
disamb-stmt-expr.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pp-exact
// Her... | // http://rust-lang.org/COPYRIGHT.
// | random_line_split |
disamb-stmt-expr.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 wsucc(_n: int) -> int { id(|| { 1 }) - 0 }
fn main() { }
| { f() } | identifier_body |
disamb-stmt-expr.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 |
nested-non-tuple-tuple-struct.rs | pub struct S(f32, f32);
pub enum E {
V(f32, f32),
}
fn | () {
let _x = (S { x: 1.0, y: 2.0 }, S { x: 3.0, y: 4.0 });
//~^ ERROR struct `S` has no field named `x`
//~| ERROR struct `S` has no field named `y`
//~| ERROR struct `S` has no field named `x`
//~| ERROR struct `S` has no field named `y`
let _y = (E::V { x: 1.0, y: 2.0 }, E::V { x: 3.0, y: 4.0... | main | identifier_name |
nested-non-tuple-tuple-struct.rs | }
fn main() {
let _x = (S { x: 1.0, y: 2.0 }, S { x: 3.0, y: 4.0 });
//~^ ERROR struct `S` has no field named `x`
//~| ERROR struct `S` has no field named `y`
//~| ERROR struct `S` has no field named `x`
//~| ERROR struct `S` has no field named `y`
let _y = (E::V { x: 1.0, y: 2.0 }, E::V { x: 3... | pub struct S(f32, f32);
pub enum E {
V(f32, f32), | random_line_split | |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::thread;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the window
w: u3... |
}
/// Get x
// TODO: Sync with window movements
pub fn x(&self) -> i32 {
self.x
}
/// Get y
// TODO: Sync with window movements
pub fn y(&self) -> i32 {
self.y
}
/// Get width
pub fn width(&self) -> u32 {
self.w
}
/// Get height
pub fn... | {
// orbital://x/y/w/h/t
if let Some(path_str) = path.to_str() {
let parts: Vec<&str> = path_str.split('/').collect();
if let Some(x) = parts.get(3) {
self.x = x.to_num_signed();
}
if let Some(y) = parts.get(4) {... | conditional_block |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::thread;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the window
w: u3... | (&self) -> u32 {
self.w
}
/// Get height
pub fn height(&self) -> u32 {
self.h
}
/// Get title
pub fn title(&self) -> String {
self.t.clone()
}
/// Set title
pub fn set_title(&mut self, _: &str) {
// TODO
}
/// Draw a pixel
pub fn pixel(... | width | identifier_name |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::thread;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the window
w: u3... |
/// Set title
pub fn set_title(&mut self, _: &str) {
// TODO
}
/// Draw a pixel
pub fn pixel(&mut self, x: i32, y: i32, color: Color) {
if x >= 0 && y >= 0 && x < self.w as i32 && y < self.h as i32 {
let offset = y as u32 * self.w + x as u32;
self.data[offse... |
/// Get title
pub fn title(&self) -> String {
self.t.clone()
} | random_line_split |
window.rs | use std::fs::File;
use std::io::*;
use std::mem;
use std::slice;
use std::thread;
use std::to_num::ToNum;
use super::Event;
use super::Color;
/// A window
pub struct Window {
/// The x coordinate of the window
x: i32,
/// The y coordinate of the window
y: i32,
/// The width of the window
w: u3... |
/// Display an image
// TODO: Improve speed
pub fn image(&mut self, start_x: i32, start_y: i32, w: u32, h: u32, data: &[Color]) {
let mut i = 0;
for y in start_y..start_y + h as i32 {
for x in start_x..start_x + w as i32 {
if i < data.len() {
... | {
for y in start_y..start_y + h as i32 {
for x in start_x..start_x + w as i32 {
self.pixel(x, y, color);
}
}
} | identifier_body |
issue-2735-3.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(manage... | random_line_split | |
issue-2735-3.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 dtor_ran = @Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
}
| {
defer {
b: b
}
} | identifier_body |
issue-2735-3.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 ... | (&mut self) {
self.b.set(true);
}
}
fn defer(b: @Cell<bool>) -> defer {
defer {
b: b
}
}
pub fn main() {
let dtor_ran = @Cell::new(false);
defer(dtor_ran);
assert!(dtor_ran.get());
}
| drop | identifier_name |
packet.rs | use crate::options::*;
use nom::bytes::complete::{tag, take};
use nom::multi::{many0, many_till};
use nom::number::complete::{be_u16, be_u32, be_u8};
use std::net::Ipv4Addr;
pub enum Err<I> {
NomError(nom::Err<(I, nom::error::ErrorKind)>),
NonUtf8String,
UnrecognizedMessageType,
InvalidHlen,
}
impl<I... |
fn decode_ipv4(p: &[u8]) -> IResult<&[u8], Ipv4Addr> {
let (input, addr) = take(4u8)(p)?;
Ok((input, Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3])))
}
pub fn decode_option(input: &[u8]) -> IResult<&[u8], DhcpOption> {
let (input, code) = be_u8(input)?;
assert!(code!= END);
let (input, len) = ... | ))
} | random_line_split |
packet.rs | use crate::options::*;
use nom::bytes::complete::{tag, take};
use nom::multi::{many0, many_till};
use nom::number::complete::{be_u16, be_u32, be_u8};
use std::net::Ipv4Addr;
pub enum Err<I> {
NomError(nom::Err<(I, nom::error::ErrorKind)>),
NonUtf8String,
UnrecognizedMessageType,
InvalidHlen,
}
impl<I... | (p: &[u8]) -> IResult<&[u8], Ipv4Addr> {
let (input, addr) = take(4u8)(p)?;
Ok((input, Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3])))
}
pub fn decode_option(input: &[u8]) -> IResult<&[u8], DhcpOption> {
let (input, code) = be_u8(input)?;
assert!(code!= END);
let (input, len) = be_u8(input)?;
... | decode_ipv4 | identifier_name |
client.rs | // Rust JSON-RPC Library
// Written in 2015 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warran... |
// Send request
let client = HyperClient::new();
let request = client.post(&self.url).headers(headers).body(&request);
let stream = try!(request.send().map_err(Error::Hyper));
json::de::from_reader(stream).map_err(Error::Json)
// TODO check nonces match
}
/// ... | {
headers.set(Authorization(Basic {
username: user.clone(),
password: self.pass.clone()
}));
} | conditional_block |
client.rs | // Rust JSON-RPC Library
// Written in 2015 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warran... | (url: String, user: Option<String>, pass: Option<String>) -> Client {
// Check that if we have a password, we have a username; other way around is ok
debug_assert!(pass.is_none() || user.is_some());
Client {
url: url,
user: user,
pass: pass,
nonce... | new | identifier_name |
client.rs | // Rust JSON-RPC Library
// Written in 2015 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warran... | pass: pass,
nonce: 0
}
}
/// Sends a request to a client
pub fn send_request(&self, request: &Request) -> Result<Response, Error> {
// Build request
let request = json::to_string(&request).unwrap();
// Setup connection
let mut headers = Heade... | random_line_split | |
noise.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, x: i32, y: i32) -> Vec2 {
let idx = self.permutations[(x & 255) as usize] +
self.permutations[(y & 255) as usize];
self.rgradients[(idx & 255) as usize]
}
fn get_gradients(&self, x: f32, y: f32) -> ([Vec2; 4], [Vec2; 4]) {
let x0f = x.floor();
let y0f... | get_gradient | identifier_name |
noise.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 ... | for x in 0..256 {
let idx = (pixels[y*256+x] / 0.2) as usize;
print!("{}", symbols[idx]);
}
print!("\n");
}
} | }
for y in 0..256 { | random_line_split |
chunk.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 anyhow::{bail, Error, Result};
use bytes_old::{BufMut, Bytes, BytesMut};
use tokio_codec::{Decoder, Encoder};
use crate::errors::Error... | () {
let mut buf = BytesMut::with_capacity(4);
buf.put_i32_be(-1);
let mut decoder = ChunkDecoder;
let chunk = decoder.decode(&mut buf).unwrap().unwrap();
assert_eq!(chunk, Chunk::error());
assert!(!chunk.is_normal());
assert!(!chunk.is_empty());
assert!... | test_error_chunk | identifier_name |
chunk.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 anyhow::{bail, Error, Result};
use bytes_old::{BufMut, Bytes, BytesMut};
use tokio_codec::{Decoder, Encoder};
use crate::errors::Error... | use assert_matches::assert_matches;
use futures::compat::Future01CompatExt;
use futures_old::{stream, Future, Sink, Stream};
use quickcheck::{quickcheck, TestResult};
use tokio_codec::{FramedRead, FramedWrite};
use super::*;
#[test]
fn test_empty_chunk() {
let mut buf = BytesMu... | #[cfg(test)]
mod test {
use std::io::Cursor;
| random_line_split |
mod.rs | use std::fmt;
use std::iter;
pub mod persistence;
pub mod editor;
pub mod util;
#[derive(Debug)]
pub struct Note {
pub id: Option<isize>,
pub name: String,
pub content: String
}
| impl fmt::Display for Note {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let _ = match self.id {
Some(id) => write!(f, "{}. ", id),
None => write!(f, "[unsaved] "),
};
write!(f, "{}\n{}", self.name, self.content)
}
}
impl Note {
pub fn new(id: ... | random_line_split | |
mod.rs | use std::fmt;
use std::iter;
pub mod persistence;
pub mod editor;
pub mod util;
#[derive(Debug)]
pub struct | {
pub id: Option<isize>,
pub name: String,
pub content: String
}
impl fmt::Display for Note {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let _ = match self.id {
Some(id) => write!(f, "{}. ", id),
None => write!(f, "[unsaved] "),
};
write!... | Note | identifier_name |
mod.rs | use std::fmt;
use std::iter;
pub mod persistence;
pub mod editor;
pub mod util;
#[derive(Debug)]
pub struct Note {
pub id: Option<isize>,
pub name: String,
pub content: String
}
impl fmt::Display for Note {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let _ = match self.id {
... |
pub fn as_markdown(&self) -> String {
let mut ret = String::new();
ret.push_str(&self.name);
ret.push_str("\n");
let underline: String = iter::repeat("=").take(self.name.len()).collect();
ret.push_str(&underline);
ret.push_str("\n");
ret.push_str(&self.conte... | {
Note { id: id, name: name.to_string(), content: content.to_string() }
} | identifier_body |
sha2.rs | // Copyright (c) 2018-2019, The Tor Project, Inc.
// Copyright (c) 2018, isis agora lovecruft
// See LICENSE for licensing information
//! Hash Digests and eXtendible Output Functions (XOFs)
pub use digest::Digest;
use digest::generic_array::typenum::U32;
use digest::generic_array::typenum::U64;
use digest::generic_... | ///
/// # C_RUST_COUPLED
///
/// * `crypto_digest_dup`
#[derive(Clone)]
pub struct Sha512 {
engine: CryptoDigest,
}
/// Construct a new, default instance of a `Sha512` hash digest function.
///
/// # Examples
///
/// ```rust,no_run
/// use crypto::digests::sha2::{Sha512, Digest};
///
/// let mut hasher: Sha512 = S... | random_line_split | |
sha2.rs | // Copyright (c) 2018-2019, The Tor Project, Inc.
// Copyright (c) 2018, isis agora lovecruft
// See LICENSE for licensing information
//! Hash Digests and eXtendible Output Functions (XOFs)
pub use digest::Digest;
use digest::generic_array::typenum::U32;
use digest::generic_array::typenum::U64;
use digest::generic_... |
}
impl BlockInput for Sha512 {
type BlockSize = BlockSize;
}
/// Input `msg` into the digest.
///
/// # Examples
///
/// ```rust,no_run
/// use crypto::digests::sha2::{Sha512, Digest};
///
/// let mut hasher: Sha512 = Sha512::default();
///
/// hasher.input(b"foo");
/// hasher.input(b"bar");
/// ```
impl Input f... | {
Sha512 {
engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_512)),
}
} | identifier_body |
sha2.rs | // Copyright (c) 2018-2019, The Tor Project, Inc.
// Copyright (c) 2018, isis agora lovecruft
// See LICENSE for licensing information
//! Hash Digests and eXtendible Output Functions (XOFs)
pub use digest::Digest;
use digest::generic_array::typenum::U32;
use digest::generic_array::typenum::U64;
use digest::generic_... | () -> Sha256 {
Sha256 {
engine: CryptoDigest::new(Some(DigestAlgorithm::SHA2_256)),
}
}
}
impl BlockInput for Sha256 {
type BlockSize = BlockSize;
}
/// Input `msg` into the digest.
///
/// # Examples
///
/// ```rust,no_run
/// use crypto::digests::sha2::{Sha256, Digest};
///
/// l... | default | identifier_name |
value.rs | use serde::Serialize;
use serde_json::value::{to_value, Value as Json};
pub(crate) static DEFAULT_VALUE: Json = Json::Null;
/// A JSON wrapper designed for handlebars internal use case
///
/// * Constant: the JSON value hardcoded into template
/// * Context: the JSON value referenced in your provided data context
//... |
}
/// Render Json data with default format
pub trait JsonRender {
fn render(&self) -> String;
}
pub trait JsonTruthy {
fn is_truthy(&self, include_zero: bool) -> bool;
}
impl JsonRender for Json {
fn render(&self) -> String {
match *self {
Json::String(ref s) => s.to_string(),
... | {
self.value.render()
} | identifier_body |
value.rs | use serde::Serialize;
use serde_json::value::{to_value, Value as Json};
pub(crate) static DEFAULT_VALUE: Json = Json::Null;
/// A JSON wrapper designed for handlebars internal use case
///
/// * Constant: the JSON value hardcoded into template
/// * Context: the JSON value referenced in your provided data context
//... | }
/// Render Json data with default format
pub trait JsonRender {
fn render(&self) -> String;
}
pub trait JsonTruthy {
fn is_truthy(&self, include_zero: bool) -> bool;
}
impl JsonRender for Json {
fn render(&self) -> String {
match *self {
Json::String(ref s) => s.to_string(),
... | self.value.render()
} | random_line_split |
value.rs | use serde::Serialize;
use serde_json::value::{to_value, Value as Json};
pub(crate) static DEFAULT_VALUE: Json = Json::Null;
/// A JSON wrapper designed for handlebars internal use case
///
/// * Constant: the JSON value hardcoded into template
/// * Context: the JSON value referenced in your provided data context
//... | (&self) -> bool {
matches!(self, ScopedJson::Missing)
}
pub fn into_derived(self) -> ScopedJson<'reg, 'rc> {
let v = self.as_json();
ScopedJson::Derived(v.clone())
}
pub fn context_path(&self) -> Option<&Vec<String>> {
match self {
ScopedJson::Context(_, ref... | is_missing | identifier_name |
arc_types.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/. */
//! This file lists all arc FFI types and defines corresponding addref
//! and release functions. This list corres... | impl_arc_ffi!(Locked<CounterStyleRule> => RawServoCounterStyleRule
[Servo_CounterStyleRule_AddRef, Servo_CounterStyleRule_Release]);
// RuleNode is a Arc-like type but it does not use Arc.
impl StrongRuleNode {
pub fn into_strong(self) -> RawServoRuleNodeStrong {
let ptr = self.ptr();
... | random_line_split | |
arc_types.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/. */
//! This file lists all arc FFI types and defines corresponding addref
//! and release functions. This list corres... |
pub fn from_ffi<'a>(ffi: &'a &RawServoRuleNode) -> &'a Self {
unsafe { &*(ffi as *const &RawServoRuleNode as *const StrongRuleNode) }
}
}
#[no_mangle]
pub unsafe extern "C" fn Servo_RuleNode_AddRef(obj: &RawServoRuleNode) {
mem::forget(StrongRuleNode::from_ffi(&obj).clone());
}
#[no_mangle]
pub ... | {
let ptr = self.ptr();
mem::forget(self);
unsafe { mem::transmute(ptr) }
} | identifier_body |
arc_types.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/. */
//! This file lists all arc FFI types and defines corresponding addref
//! and release functions. This list corres... | (obj: &ComputedValues) {
ArcBorrow::from_ref(obj).with_arc(|a: &Arc<ComputedValues>| {
let _: Arc<ComputedValues> = ptr::read(a);
});
}
impl From<Arc<ComputedValues>> for Strong<ComputedValues> {
fn from(arc: Arc<ComputedValues>) -> Self {
unsafe { mem::transmute(Arc::into_raw_offset(arc)) ... | Servo_ComputedStyle_Release | identifier_name |
child_process.rs | // Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
fn new_internal(
command: Arc<Mutex<std::process::Command>>,
stderr_sender: Arc<Mutex<mpsc::Sender<String>>>,
) -> Result<ChildProcess, Error> {
let process = command.lock().unwrap().spawn();
let mut process = match process {
Ok(c) => c,
Err(error) => ba... | {
// Avoid a fork bomb. We could call runtime_hook here but then all the work that we did up
// to this point would be wasted. Also, it's possible that we could already have started
// threads, which could get messy.
if std::env::var(runtime::EVCXR_IS_RUNTIME_VAR).is_ok() {
b... | identifier_body |
child_process.rs | // Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | }
});
let stdin = process.stdin.take();
Ok(ChildProcess {
process,
stdout,
stdin,
command,
stderr_sender,
})
}
/// Terminates this process if it hasn't already, then restarts
pub(crate) fn restart(&mut ... | random_line_split | |
child_process.rs | // Copyright 2020 The Evcxr Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (&mut self) -> Result<String, Error> {
Ok(self
.stdout
.next()
.ok_or_else(|| self.get_termination_error())??)
}
fn get_termination_error(&mut self) -> Error {
// Wait until the stderr handling thread has released its lock on stderr_sender, which it
// w... | recv_line | identifier_name |
aarch64.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 cty::{c_int};
use {VarArg};
use core::{mem, ptr};
use core::intrinsics::{type_id};
#[repr(C)]
pub struct VarArgs... | }
}
let mut ptr = self.__stack;
self.__stack = ptr.add(8);
if cfg!(target_endian = "big") {
ptr = ptr.add(8 - mem::size_of::<T>());
}
ptr::read(ptr as *mut T)
}
}
unsafe fn fp<T>() -> bool {
let id = type_id::<T>();
id == type_id::<f3... | if cfg!(target_endian = "big") {
offs += 8 - mem::size_of::<T>() as isize
}
return ptr::read(self.__gr_top.offset(offs) as *mut T); | random_line_split |
aarch64.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 cty::{c_int};
use {VarArg};
use core::{mem, ptr};
use core::intrinsics::{type_id};
#[repr(C)]
pub struct VarArgs... |
let mut ptr = self.__stack;
self.__stack = ptr.add(8);
if cfg!(target_endian = "big") {
ptr = ptr.add(8 - mem::size_of::<T>());
}
ptr::read(ptr as *mut T)
}
}
unsafe fn fp<T>() -> bool {
let id = type_id::<T>();
id == type_id::<f32>() || id == type_id::... | {
let mut offs = self.__gr_offs as isize;
if offs <= -8 {
self.__gr_offs += 8;
if cfg!(target_endian = "big") {
offs += 8 - mem::size_of::<T>() as isize
}
return ptr::read(self.__gr_top.offset(offs) as *mut T);
... | conditional_block |
aarch64.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 cty::{c_int};
use {VarArg};
use core::{mem, ptr};
use core::intrinsics::{type_id};
#[repr(C)]
pub struct VarArgs... | <T>() -> bool {
let id = type_id::<T>();
id == type_id::<f32>() || id == type_id::<f64>()
}
| fp | identifier_name |
aarch64.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 cty::{c_int};
use {VarArg};
use core::{mem, ptr};
use core::intrinsics::{type_id};
#[repr(C)]
pub struct VarArgs... |
let mut ptr = self.__stack;
self.__stack = ptr.add(8);
if cfg!(target_endian = "big") {
ptr = ptr.add(8 - mem::size_of::<T>());
}
ptr::read(ptr as *mut T)
}
}
unsafe fn fp<T>() -> bool {
let id = type_id::<T>();
id == type_id::<f32>() || id == type_id::... | {
if fp::<T>() {
let mut offs = self.__vr_offs as isize;
if offs <= -16 {
self.__vr_offs += 16;
if cfg!(target_endian = "big") {
offs += 16 - mem::size_of::<T>() as isize;
}
return ptr::read(self.__vr_top... | 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/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of ... | Reflow,
DOMEvent,
}
/// Messages to process in a particular script task, as instructed by a devtools client.
#[derive(Deserialize, Serialize)]
pub enum DevtoolScriptControlMsg {
EvaluateJS(PipelineId, String, IpcSender<EvaluateJSReply>),
GetRootNode(PipelineId, IpcSender<NodeInfo>),
GetDocumentElem... | pub stack: Option<Vec<()>>,
}
#[derive(PartialEq, Eq, Hash, Clone, Deserialize, Serialize)]
pub enum TimelineMarkerType { | 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/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of ... | () -> PreciseTime {
PreciseTime(time::precise_time_ns())
}
pub fn to(&self, later: PreciseTime) -> Duration {
Duration::nanoseconds((later.0 - self.0) as i64)
}
}
| now | identifier_name |
texture_animator.rs | use resources::AnimatedTexture;
use rand::{Rng, thread_rng}; | randomize: (bool, bool),
tex_width: u32,
current: u32,
delay: f32,
timer: f32,
rect: IntRect,
}
impl TextureAnimator {
pub fn new(anim_tex: &AnimatedTexture) -> TextureAnimator {
let size = anim_tex.tex.size();
let mut t = TextureAnimator {
n_frames: anim_tex.n_... | use sfml::graphics::IntRect;
pub struct TextureAnimator {
n_frames: u32,
step: i32, | random_line_split |
texture_animator.rs | use resources::AnimatedTexture;
use rand::{Rng, thread_rng};
use sfml::graphics::IntRect;
pub struct TextureAnimator {
n_frames: u32,
step: i32,
randomize: (bool, bool),
tex_width: u32,
current: u32,
delay: f32,
timer: f32,
rect: IntRect,
}
impl TextureAnimator {
pub fn new(anim_te... | else {
(self.current as i32 * self.step, self.step)
};
self.rect = IntRect::new(left, top, width, height);
}
/*
pub fn n_frames(&self) -> u32 {
self.n_frames
}
pub fn current(&self) -> u32 {
self.current
}
*/
}
| {
((self.current as i32 + 1) * self.step, -self.step)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.