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 |
|---|---|---|---|---|
polygon.rs | //! Draw polygon
use types::Color;
use {types, triangulation, Graphics, DrawState};
use math::{Matrix2d, Scalar};
/// A polygon
#[derive(Copy, Clone)]
pub struct Polygon {
/// The color of the polygon
pub color: Color,
}
impl Polygon {
/// Creates new polygon
pub fn new(color: Color) -> Polygon {
... | (mut self, color: Color) -> Self {
self.color = color;
self
}
/// Draws polygon using the default method.
#[inline(always)]
pub fn draw<G>(&self,
polygon: types::Polygon,
draw_state: &DrawState,
transform: Matrix2d,
... | color | identifier_name |
polygon.rs | //! Draw polygon
use types::Color;
use {types, triangulation, Graphics, DrawState};
use math::{Matrix2d, Scalar};
/// A polygon
#[derive(Copy, Clone)]
pub struct Polygon {
/// The color of the polygon
pub color: Color,
}
impl Polygon {
/// Creates new polygon
pub fn new(color: Color) -> Polygon {
... | transform: Matrix2d,
g: &mut G)
where G: Graphics
{
g.polygon_tween_lerp(self, polygons, tween_factor, draw_state, transform);
}
/// Draws tweened polygon with linear interpolation, using triangulation.
pub fn draw_tween_lerp_t... | #[inline(always)]
pub fn draw_tween_lerp<G>(&self,
polygons: types::Polygons,
tween_factor: Scalar,
draw_state: &DrawState, | random_line_split |
bench.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 ... |
}
str::from_utf8(bytes.as_slice()).unwrap().to_strbuf()
}
throughput!(easy0_32, easy0(), 32)
throughput!(easy0_1K, easy0(), 1<<10)
throughput!(easy0_32K, easy0(), 32<<10)
throughput!(easy1_32, easy1(), 32)
throughput!(easy1_1K, easy1(), 1<<10)
throughput!(easy1_32K, easy1(), 32<<10)
throughput!(medium_32, m... | {
*b = '\n' as u8
} | conditional_block |
bench.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 ... | )
fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") }
fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
#[allow(deprecated_owned_vector)]
fn ... | b.bytes = $size;
b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") });
}
); | random_line_split |
bench.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 ... |
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap();
let text = "a".repeat(n);
bench_assert_match(b, re, text);
}
#[bench]
fn literal(b: &mut Bencher) {
let re = regex!("y");
let text = "x".repeat(50) + "y";
bench_assert_... | {
b.iter(|| if !re.is_match(text) { fail!("no match") });
} | identifier_body |
bench.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 ... | (b: &mut Bencher) {
let re = regex!("y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn not_literal(b: &mut Bencher) {
let re = regex!(".y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class(b: &mut Bencher) {
let... | literal | identifier_name |
client.rs | use abox = sodiumoxide::crypto::asymmetricbox;
use capnp;
use capnp::message::{MessageReader, MessageBuilder, ReaderOptions};
use capnp::serialize_packed;
use std::io;
use std::str;
use std::time::duration::Duration;
use nanomsg::{NanoSocket};
use nanomsg::{AF_SP,NN_PAIR};
use schema::request_capnp;
use schema::repl... | () {
info!("Connecting to {}", ::client_addr);
let sock = NanoSocket::new(AF_SP, NN_PAIR).unwrap();
sock.connect(::client_addr).unwrap();
let (pub_key, sec_key) = abox::gen_keypair();
let mut req_i = 0u32;
loop {
let req_str = format!("Request {}", req_i);
debug!("Sending: {... | client | identifier_name |
client.rs | use abox = sodiumoxide::crypto::asymmetricbox;
use capnp;
use capnp::message::{MessageReader, MessageBuilder, ReaderOptions};
use capnp::serialize_packed;
use std::io;
use std::str;
use std::time::duration::Duration;
use nanomsg::{NanoSocket};
use nanomsg::{AF_SP,NN_PAIR};
use schema::request_capnp;
use schema::repl... | }
let mut writer = io::MemWriter::new();
serialize_packed::write_packed_message_unbuffered(&mut writer, &message).unwrap();
sock.send(writer.unwrap().as_slice()).unwrap();
let rep = sock.recv().unwrap();
let mut reader = io::MemReader::new(rep);
let reader = ser... | {
info!("Connecting to {}", ::client_addr);
let sock = NanoSocket::new(AF_SP, NN_PAIR).unwrap();
sock.connect(::client_addr).unwrap();
let (pub_key, sec_key) = abox::gen_keypair();
let mut req_i = 0u32;
loop {
let req_str = format!("Request {}", req_i);
debug!("Sending: {}",... | identifier_body |
client.rs | use abox = sodiumoxide::crypto::asymmetricbox;
use capnp;
use capnp::message::{MessageReader, MessageBuilder, ReaderOptions};
use capnp::serialize_packed;
use std::io;
use std::str;
use std::time::duration::Duration;
use nanomsg::{NanoSocket};
use nanomsg::{AF_SP,NN_PAIR};
use schema::request_capnp;
use schema::repl... |
let rep_nonce = abox::Nonce::from_slice_by_ref(rep.get_nonce()).unwrap();
let rep_key = abox::PublicKey::from_slice_by_ref(rep.get_key()).unwrap();
match abox::open(rep.get_data(), rep_nonce, rep_key, &sec_key) {
Some(data) => match str::from_utf8(data.as_slice()) {
... | let rep = sock.recv().unwrap();
let mut reader = io::MemReader::new(rep);
let reader = serialize_packed::new_reader_unbuffered(&mut reader, ReaderOptions::new()).unwrap();
let rep = reader.get_root::<reply_capnp::Reply::Reader>(); | random_line_split |
main.rs | extern crate roman_army;
use roman_army::ComponentUnit;
use roman_army::primitives::{ Archer, Infantryman, Horseman };
use roman_army::composite::CompositeUnit;
fn main() {
let mut army = CompositeUnit::new();
for _ in 0..4 {
let legion = create_legion();
army.add_unit(Box::new(legion));
... | () -> CompositeUnit {
let mut composite_legion = CompositeUnit::new();
for _ in 0..3000 {
composite_legion.add_unit(Box::new(Infantryman));
}
for _ in 0..1200 {
composite_legion.add_unit(Box::new(Archer));
}
for _ in 0..300 {
composite_legion.add_unit(Box::new(Horseman... | create_legion | identifier_name |
main.rs | extern crate roman_army;
use roman_army::ComponentUnit;
use roman_army::primitives::{ Archer, Infantryman, Horseman };
use roman_army::composite::CompositeUnit;
fn main() | army.remove(0);
let legions = army.get_units();
println!("Roman army damaging strength is {}", army.get_strength());
println!("Roman army has {} legions", legions.len());
}
fn create_legion() -> CompositeUnit {
let mut composite_legion = CompositeUnit::new();
for _ in 0..3000 {
compo... | {
let mut army = CompositeUnit::new();
for _ in 0..4 {
let legion = create_legion();
army.add_unit(Box::new(legion));
}
{
let legions = army.get_units();
println!("Roman army damaging strength is {}", army.get_strength());
println!("Roman army has {} legions\n",... | identifier_body |
main.rs | extern crate roman_army;
use roman_army::ComponentUnit;
use roman_army::primitives::{ Archer, Infantryman, Horseman };
use roman_army::composite::CompositeUnit;
fn main() {
let mut army = CompositeUnit::new();
for _ in 0..4 {
let legion = create_legion();
army.add_unit(Box::new(legion));
... |
{
let legion = army.get_unit(0);
println!("Roman legion damaging strength is {}", legion.get_strength());
println!("Roman legion has {} units\n", legion.get_units().len());
}
army.remove(0);
let legions = army.get_units();
println!("Roman army damaging strength is {}", arm... | random_line_split | |
area.rs | // Copyright (c) 2017-2021 Linaro LTD
// Copyright (c) 2018-2019 JUUL Labs
// Copyright (c) 2019 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
//! Describe flash areas.
use simflash::{Flash, SimFlash, Sector};
use std::ptr;
use std::collections::HashMap;
/// Structure to build up the boot area table.
#[deriv... |
let mut area = vec![];
for sector in &self.sectors[&dev_id] {
if len == 0 {
break;
};
if base > sector.base + sector.size - 1 {
continue;
}
if sector.base!= base {
panic!("Image does not start ... | {
panic!("Flash areas not added in order");
} | conditional_block |
area.rs | // Copyright (c) 2017-2021 Linaro LTD
// Copyright (c) 2018-2019 JUUL Labs
// Copyright (c) 2019 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
//! Describe flash areas.
use simflash::{Flash, SimFlash, Sector};
use std::ptr;
use std::collections::HashMap;
/// Structure to build up the boot area table.
#[deriv... |
impl Default for CArea {
fn default() -> CArea {
CArea {
areas: ptr::null(),
whole: Default::default(),
id: FlashId::BootLoader,
num_areas: 0,
}
}
}
/// Flash area map.
#[repr(u8)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[allow(dead_code)]
... | num_areas: u32,
// FIXME: is this not already available on whole/areas?
id: FlashId,
} | random_line_split |
area.rs | // Copyright (c) 2017-2021 Linaro LTD
// Copyright (c) 2018-2019 JUUL Labs
// Copyright (c) 2019 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
//! Describe flash areas.
use simflash::{Flash, SimFlash, Sector};
use std::ptr;
use std::collections::HashMap;
/// Structure to build up the boot area table.
#[deriv... |
/// Add a slot to the image. The slot must align with erasable units in the flash device.
/// Panics if the description is not valid. There are also bootloader assumptions that the
/// slots are PRIMARY_SLOT, SECONDARY_SLOT, and SCRATCH in that order.
pub fn add_image(&mut self, base: usize, len: us... | {
self.sectors.insert(id, flash.sector_iter().collect());
} | identifier_body |
area.rs | // Copyright (c) 2017-2021 Linaro LTD
// Copyright (c) 2018-2019 JUUL Labs
// Copyright (c) 2019 Arm Limited
//
// SPDX-License-Identifier: Apache-2.0
//! Describe flash areas.
use simflash::{Flash, SimFlash, Sector};
use std::ptr;
use std::collections::HashMap;
/// Structure to build up the boot area table.
#[deriv... | () -> AreaDesc {
AreaDesc {
areas: vec![],
whole: vec![],
sectors: HashMap::new(),
}
}
pub fn add_flash_sectors(&mut self, id: u8, flash: &SimFlash) {
self.sectors.insert(id, flash.sector_iter().collect());
}
/// Add a slot to the image. The... | new | identifier_name |
build.rs | extern crate amq_protocol;
use amq_protocol::codegen::*;
use std::collections::BTreeMap;
use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
fn main() {
let out_dir = env::var("OUT_DIR").expect("OUT_DIR is not defined");
let dest_path = Path::new(&out_dir).join("generate... | let mut full_tpl = String::new();
let mut api_tpl = String::new();
std::fs::File::open("templates/main.rs").expect("Failed to open main template").read_to_string(&mut full_tpl).expect("Failed to read main template");
std::fs::File::open("templates/api.rs").expect("Failed to open main template").read_to_... | let mut f = File::create(&dest_path).expect("Failed to create generated.rs");
let mut f2 = File::create(&dest_path2).expect("Failed to create api.rs"); | random_line_split |
build.rs | extern crate amq_protocol;
use amq_protocol::codegen::*;
use std::collections::BTreeMap;
use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
fn main() | writeln!(f2, "{}", handlebars.render("api", &data).expect("Failed to render api template")).expect("Failed to write api.rs");
}
| {
let out_dir = env::var("OUT_DIR").expect("OUT_DIR is not defined");
let dest_path = Path::new(&out_dir).join("generated.rs");
let dest_path2 = Path::new(&out_dir).join("api.rs");
let mut f = File::create(&dest_path).expect("Failed to create generated.rs");
let mut f2 = File:... | identifier_body |
build.rs | extern crate amq_protocol;
use amq_protocol::codegen::*;
use std::collections::BTreeMap;
use std::env;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
fn | () {
let out_dir = env::var("OUT_DIR").expect("OUT_DIR is not defined");
let dest_path = Path::new(&out_dir).join("generated.rs");
let dest_path2 = Path::new(&out_dir).join("api.rs");
let mut f = File::create(&dest_path).expect("Failed to create generated.rs");
let mut f2 = Fi... | main | identifier_name |
cli.rs | use clap::{crate_version, App, AppSettings, Arg};
pub fn build_cli() -> App<'static,'static> | )
.arg(
Arg::with_name("test")
.required(false)
.long("test")
.short("t")
.help("Test to see if conversion is required")
.takes_value(false),
)
.arg(
Arg::with_name("file")
.re... | {
App::new("chromecastise")
.version(crate_version!())
.author("Stuart Moss <samoss@gmail.com>")
.setting(AppSettings::ArgRequiredElseHelp)
.arg(
Arg::with_name("mp4")
.long("mp4")
.short("a")
.help("Use mp4 as the output co... | identifier_body |
cli.rs | use clap::{crate_version, App, AppSettings, Arg};
pub fn build_cli() -> App<'static,'static> {
App::new("chromecastise")
.version(crate_version!())
.author("Stuart Moss <samoss@gmail.com>")
.setting(AppSettings::ArgRequiredElseHelp)
.arg(
Arg::with_name("mp4")
... | .help("Use mp4 as the output container format")
.conflicts_with("mkv")
.takes_value(false),
)
.arg(
Arg::with_name("mkv")
.long("mkv")
.short("b")
.help("Use mkv as the output container format")
... | random_line_split | |
cli.rs | use clap::{crate_version, App, AppSettings, Arg};
pub fn | () -> App<'static,'static> {
App::new("chromecastise")
.version(crate_version!())
.author("Stuart Moss <samoss@gmail.com>")
.setting(AppSettings::ArgRequiredElseHelp)
.arg(
Arg::with_name("mp4")
.long("mp4")
.short("a")
.help("Use ... | build_cli | identifier_name |
mod.rs | use system::OS;
mod manager;
pub mod scoped;
// #[macro_use]mod local;
// pub use self::local::{LocalKey, LocalKeyState};
/// Cooperatively gives up a timeslice to the OS scheduler.
pub fn yield_now() {
OS::yield_thread()
}
/// Blocks unless or until the current thread's token is made available.
///
/// Every t... | /// being acquired).
///
/// A call to `park` does not guarantee that the thread will remain parked
/// forever, and callers should be prepared for this possibility.
///
/// See the [module documentation][thread] for more detail.
///
/// [thread]: index.html
// The implementation currently uses the trivial strategy of ... | /// [unpark]: struct.Thread.html#method.unpark
///
/// The API is typically used by acquiring a handle to the current thread,
/// placing that handle in a shared data structure so that other threads can
/// find it, and then parking (in a loop with a check for the token actually | random_line_split |
mod.rs | use system::OS;
mod manager;
pub mod scoped;
// #[macro_use]mod local;
// pub use self::local::{LocalKey, LocalKeyState};
/// Cooperatively gives up a timeslice to the OS scheduler.
pub fn yield_now() {
OS::yield_thread()
}
/// Blocks unless or until the current thread's token is made available.
///
/// Every t... |
pub use self::manager::{collect, current, JoinHandle, Thread, spawn}; | {
OS::suspend_thread(OS::get_current_thread());
} | identifier_body |
mod.rs | use system::OS;
mod manager;
pub mod scoped;
// #[macro_use]mod local;
// pub use self::local::{LocalKey, LocalKeyState};
/// Cooperatively gives up a timeslice to the OS scheduler.
pub fn | () {
OS::yield_thread()
}
/// Blocks unless or until the current thread's token is made available.
///
/// Every thread is equipped with some basic low-level blocking support, via
/// the `park()` function and the [`unpark()`][unpark] method. These can be
/// used as a more CPU-efficient implementation of a spinlo... | yield_now | identifier_name |
tests.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 ... | {
let a = hexfloat!("0x1.999999999999ap-4");
assert_eq!(a, 0.1f64);
let b = hexfloat!("-0x1.fffp-4", f32);
assert_eq!(b, -0.12498474_f32);
let c = hexfloat!("0x.12345p5", f64);
let d = hexfloat!("0x0.12345p5", f64);
assert_eq!(c,d);
let f = hexfloat!("0x10.p4", f32);
let g = hexfloat... | identifier_body | |
tests.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 ... | () {
let a = hexfloat!("0x1.999999999999ap-4");
assert_eq!(a, 0.1f64);
let b = hexfloat!("-0x1.fffp-4", f32);
assert_eq!(b, -0.12498474_f32);
let c = hexfloat!("0x.12345p5", f64);
let d = hexfloat!("0x0.12345p5", f64);
assert_eq!(c,d);
let f = hexfloat!("0x10.p4", f32);
let g = hexfl... | main | identifier_name |
tests.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 ... | assert_eq!(f,g);
} | random_line_split | |
text.rs | /// Divide a string into the longest slice that fits within maximum line
/// length and the rest of the string.
///
/// Place the split before a whitespace or after a hyphen if possible. Any
/// whitespace between the two segments is trimmed. Newlines will cause a
/// segment split when encountered.
pub fn split_line<'... | assert!(!eat_whitespace);
// Invariant: The length of the string processed up to this point is
// still short enough to return.
// Encounter the first whitespace, set head_end marker.
if c.is_whitespace() {
head_end = i;
tail_start = i + 1;
i... | }
// We're either just encountering the first whitespace after a block
// of text, or over non-whitespace text. | random_line_split |
text.rs | /// Divide a string into the longest slice that fits within maximum line
/// length and the rest of the string.
///
/// Place the split before a whitespace or after a hyphen if possible. Any
/// whitespace between the two segments is trimmed. Newlines will cause a
/// segment split when encountered.
pub fn split_line<'... |
assert!(head.len() > 0, "Line splitter caught in infinite loop");
assert!(tail.len() < text.len(), "Line splitter not shrinking string");
result = result + head;
// Must preserve a hard newline at the end if the input string had
// one. The else branch checks for the very last c... | { break; } | conditional_block |
text.rs | /// Divide a string into the longest slice that fits within maximum line
/// length and the rest of the string.
///
/// Place the split before a whitespace or after a hyphen if possible. Any
/// whitespace between the two segments is trimmed. Newlines will cause a
/// segment split when encountered.
pub fn split_line<'... | (&mut self) -> Option<(char, i32, i32)> {
loop {
match self.iter.next() {
None => { return None }
Some(c) if c == '\n' => { self.y += 1; self.x = 0; }
Some(c) if (c as u32) < 32 => { }
Some(c) => { self.x += 1; return Some((c, self.x - ... | next | identifier_name |
text.rs | /// Divide a string into the longest slice that fits within maximum line
/// length and the rest of the string.
///
/// Place the split before a whitespace or after a hyphen if possible. Any
/// whitespace between the two segments is trimmed. Newlines will cause a
/// segment split when encountered.
pub fn split_line<'... |
pub struct Map2DIterator<T> {
/// Input iterator
iter: T,
x: i32,
y: i32,
}
impl<T: Iterator<Item=char>> Iterator for Map2DIterator<T> {
type Item = (char, i32, i32);
fn next(&mut self) -> Option<(char, i32, i32)> {
loop {
match self.iter.next() {
None => ... | {
let mut result = String::new();
loop {
let (head, tail) = split_line(text, char_width, max_len);
if head.len() == 0 && tail.len() == 0 { break; }
assert!(head.len() > 0, "Line splitter caught in infinite loop");
assert!(tail.len() < text.len(), "Line splitter not shrinking stri... | identifier_body |
components.rs | use std::convert::{Into};
use std::collections::HashSet;
use calx::{Rgba};
use location::Location;
use location_set::LocationSet;
use {Biome};
use item::{ItemType};
use ability::Ability;
use stats::Stats;
/// Dummy component to mark prototype objects
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
pub st... | (mut self, biome: Biome) -> Spawn {
self.biome = biome; self
}
/// Set the minimum depth where the entity can spawn. More powerful
/// entities should only spawn in greater depths. By default this is 1.
pub fn depth(mut self, min_depth: i32) -> Spawn {
self.min_depth = min_depth; self
... | biome | identifier_name |
components.rs | use std::convert::{Into};
use std::collections::HashSet;
use calx::{Rgba};
use location::Location;
use location_set::LocationSet;
use {Biome};
use item::{ItemType};
use ability::Ability;
use stats::Stats;
/// Dummy component to mark prototype objects
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
pub st... | }
/// Stats cache is a transient component made from adding up a mob's intrinsic
/// stats and the stat bonuses of its equipment and whatever spell effects may
/// apply.
pub type StatsCache = Option<Stats>;
/// Belong to a zone.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct Colonist {
pub ... | #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct Item {
pub item_type: ItemType,
pub ability: Ability, | random_line_split |
components.rs | use std::convert::{Into};
use std::collections::HashSet;
use calx::{Rgba};
use location::Location;
use location_set::LocationSet;
use {Biome};
use item::{ItemType};
use ability::Ability;
use stats::Stats;
/// Dummy component to mark prototype objects
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
pub st... |
/// Set the probability for this entity to spawn. Twice as large is twice
/// as common. The default is 1000.
pub fn commonness(mut self, commonness: u32) -> Spawn {
assert!(commonness > 0);
self.commonness = commonness; self
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, RustcEncoda... | {
self.min_depth = min_depth; self
} | identifier_body |
issue13359.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 ... |
fn main() {
foo(1*(1 as int));
//~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`)
bar(1*(1 as uint));
//~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`)
} | // except according to those terms.
fn foo(_s: i16) { }
fn bar(_s: u32) { } | random_line_split |
issue13359.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 ... |
fn main() {
foo(1*(1 as int));
//~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`)
bar(1*(1 as uint));
//~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`)
}
| { } | identifier_body |
issue13359.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 ... | (_s: i16) { }
fn bar(_s: u32) { }
fn main() {
foo(1*(1 as int));
//~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`)
bar(1*(1 as uint));
//~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`)
}
| foo | identifier_name |
test_code_in_readme.rs | use std::{
fs,
fs::File,
io::{Read, Write},
path::Path,
};
use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag};
use flapigen::{CppConfig, Generator, JavaConfig, LanguageConfig};
use tempfile::tempdir;
#[test]
fn test_code_in_readme() {
let _ = env_logger::try_init();
let tests = parse_read... | match token {
"" => {}
"rust" => {
info.is_rust = true;
seen_rust_tags = true
}
"should_panic" => {
info.should_panic = true;
seen_rust_tags = true
}
"ignore" => {
... | {
// Same as rustdoc
let info: &str = match info {
CodeBlockKind::Indented => "",
CodeBlockKind::Fenced(x) => x.as_ref(),
};
let tokens = info.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric()));
let mut seen_rust_tags = false;
let mut seen_other_tags = false;
le... | identifier_body |
test_code_in_readme.rs | use std::{
fs,
fs::File,
io::{Read, Write},
path::Path,
};
use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag};
use flapigen::{CppConfig, Generator, JavaConfig, LanguageConfig};
use tempfile::tempdir;
#[test]
fn test_code_in_readme() {
let _ = env_logger::try_init();
let tests = parse_read... | (info: &CodeBlockKind) -> CodeBlockInfo {
// Same as rustdoc
let info: &str = match info {
CodeBlockKind::Indented => "",
CodeBlockKind::Fenced(x) => x.as_ref(),
};
let tokens = info.split(|c: char|!(c == '_' || c == '-' || c.is_alphanumeric()));
let mut seen_rust_tags = false;
... | parse_code_block_info | identifier_name |
test_code_in_readme.rs | use std::{
fs,
fs::File,
io::{Read, Write},
path::Path,
};
use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag};
use flapigen::{CppConfig, Generator, JavaConfig, LanguageConfig};
use tempfile::tempdir;
#[test]
fn test_code_in_readme() {
let _ = env_logger::try_init();
let tests = parse_read... | let mut tests = Vec::new();
for event in parser {
match event {
Event::Start(Tag::CodeBlock(ref info)) => {
let code_block_info = parse_code_block_info(info);
if code_block_info.is_rust {
code_buffer = Some(Vec::new());
}
... | random_line_split | |
frame.rs | use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use super::super::varstack::VectorVarStack;
use super::super::objects::{ObjectRef, Code};
use super::instructions::{Instruction, InstructionDecoder};
#[derive(Debug)]
pub enum Block {
Loop(usize, usize), // begin, end
TryExcept(usize, usiz... | (object: ObjectRef, code: Code, locals: Rc<RefCell<HashMap<String, ObjectRef>>>) -> Frame {
let instructions: Vec<Instruction> = InstructionDecoder::new(code.code.iter()).into_iter().collect();
Frame {
object: object,
var_stack: VectorVarStack::new(),
block_stack: Vec... | new | identifier_name |
frame.rs | use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use super::super::varstack::VectorVarStack;
use super::super::objects::{ObjectRef, Code};
use super::instructions::{Instruction, InstructionDecoder};
#[derive(Debug)]
pub enum Block {
Loop(usize, usize), // begin, end
TryExcept(usize, usiz... | }
impl Frame {
pub fn new(object: ObjectRef, code: Code, locals: Rc<RefCell<HashMap<String, ObjectRef>>>) -> Frame {
let instructions: Vec<Instruction> = InstructionDecoder::new(code.code.iter()).into_iter().collect();
Frame {
object: object,
var_stack: VectorVarStack::new()... | pub block_stack: Vec<Block>,
pub locals: Rc<RefCell<HashMap<String, ObjectRef>>>,
pub instructions: Vec<Instruction>,
pub code: Code,
pub program_counter: usize, | random_line_split |
frame.rs | use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
use super::super::varstack::VectorVarStack;
use super::super::objects::{ObjectRef, Code};
use super::instructions::{Instruction, InstructionDecoder};
#[derive(Debug)]
pub enum Block {
Loop(usize, usize), // begin, end
TryExcept(usize, usiz... |
}
| {
let instructions: Vec<Instruction> = InstructionDecoder::new(code.code.iter()).into_iter().collect();
Frame {
object: object,
var_stack: VectorVarStack::new(),
block_stack: Vec::new(),
locals: locals,
instructions: instructions,
c... | identifier_body |
main.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... | {
unsafe {
let path = Path::new("libdylib.so");
let a = DynamicLibrary::open(Some(&path)).unwrap();
assert!(a.symbol::<isize>("fun1").is_ok());
assert!(a.symbol::<isize>("fun2").is_err());
assert!(a.symbol::<isize>("fun3").is_err());
assert!(a.symbol::<isize>("fun4").... | identifier_body | |
main.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... | } | } | random_line_split |
main.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... | () {
unsafe {
let path = Path::new("libdylib.so");
let a = DynamicLibrary::open(Some(&path)).unwrap();
assert!(a.symbol::<isize>("fun1").is_ok());
assert!(a.symbol::<isize>("fun2").is_err());
assert!(a.symbol::<isize>("fun3").is_err());
assert!(a.symbol::<isize>("fun4... | main | identifier_name |
cache.rs | use consumer::forced_string;
use std::{fs, path, process};
#[derive(Clone)]
pub struct Cache {
build: path::PathBuf,
cache: path::PathBuf,
folders: Vec<String>,
}
impl Cache {
pub fn new(build: path::PathBuf, cache: path::PathBuf) -> Cache {
let folders = vec![
"target/debug",
... | (path: &str, source: &path::Path, destination: &path::Path) -> Result<(), &'static str> {
let mut dst = destination.to_path_buf();
dst.push(path);
let _ = fs::create_dir_all(dst.as_path());
dst.pop();
let output = process::Command::new("rsync")
.arg("-aPc")
.arg("--delete")
.arg... | rsync | identifier_name |
cache.rs | use consumer::forced_string;
use std::{fs, path, process};
#[derive(Clone)]
pub struct Cache {
build: path::PathBuf,
cache: path::PathBuf,
folders: Vec<String>,
}
impl Cache {
pub fn new(build: path::PathBuf, cache: path::PathBuf) -> Cache {
let folders = vec![
"target/debug",
... |
}
| {
debug!("rsync {}: fail", path);
Err("rsync failed")
} | conditional_block |
cache.rs | use consumer::forced_string;
use std::{fs, path, process};
#[derive(Clone)]
pub struct Cache {
build: path::PathBuf,
cache: path::PathBuf,
folders: Vec<String>,
}
impl Cache {
pub fn new(build: path::PathBuf, cache: path::PathBuf) -> Cache {
let folders = vec![
"target/debug",
... | Ok(())
} else {
debug!("rsync {}: fail", path);
Err("rsync failed")
}
} | if output.status.success() {
debug!("rsync {}: ok", path); | random_line_split |
kindck-impl-type-params.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() { }
| {
let t: Box<S<String>> = box S(marker::PhantomData);
let a: Box<Gettable<String>> = t;
//~^ ERROR the trait `core::marker::Copy` is not implemented
} | identifier_body |
kindck-impl-type-params.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> T { panic!() }
}
impl<T: Send + Copy +'static> Gettable<T> for S<T> {}
fn f<T>(val: T) {
let t: S<T> = S(marker::PhantomData);
let a = &t as &Gettable<T>;
//~^ ERROR the trait `core::marker::Send` is not implemented
//~^^ ERROR the trait `core::marker::Copy` is not implemented
//~^^^ ER... | get | identifier_name |
kindck-impl-type-params.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 foo<'a>() {
let t: S<&'a isize> = S(marker::PhantomData);
let a = &t as &Gettable<&'a isize>;
//~^ ERROR does not fulfill
}
fn foo2<'a>() {
let t: Box<S<String>> = box S(marker::PhantomData);
let a = t as Box<Gettable<String>>;
//~^ ERROR the trait `core::marker::Copy` is not implemented
}
... | //~^^ ERROR the trait `core::marker::Copy` is not implemented
} | random_line_split |
negative_literal_mover.rs | //! This module literals in a GDL description such that all variables in a negative literal (i.e. a
//! `distinct` or `not` literal) have been seen in positive literals occurring before that
//! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is
//! necessary, see section 13.6 [... | let body = &mut *r.body;
body.swap(index, swap_index);
}
None => break
}
}
r
}
fn find_neg_lit_index(body: &[Literal]) -> Option<usize> {
let mut seen_vars = HashSet::new();
for (i, lit) in body.iter().enumerate() {
match lit {
... | loop {
match find_neg_lit_index(&*r.body) {
Some(index) => {
let swap_index = find_candidate_index(&*r.body, &r.body[index])
.expect("No candidate index found"); | random_line_split |
negative_literal_mover.rs | //! This module literals in a GDL description such that all variables in a negative literal (i.e. a
//! `distinct` or `not` literal) have been seen in positive literals occurring before that
//! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is
//! necessary, see section 13.6 [... |
_ => new_clauses.push(clause)
}
}
Description::new(new_clauses)
}
fn reorder_rule(mut r: Rule) -> Rule {
loop {
match find_neg_lit_index(&*r.body) {
Some(index) => {
let swap_index = find_candidate_index(&*r.body, &r.body[index])
.... | {
new_clauses.push(reorder_rule(r).into());
} | conditional_block |
negative_literal_mover.rs | //! This module literals in a GDL description such that all variables in a negative literal (i.e. a
//! `distinct` or `not` literal) have been seen in positive literals occurring before that
//! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is
//! necessary, see section 13.6 [... |
#[test]
fn test_beginning_distinct() {
let gdl = "(role you) \
(<= (foo?a?b) \
(distinct?a?b) \
(p?a) \
(q?b)) \
(p a) \
(p b) \
(q a) \
(q b) \... | {
let desc = gdl::parse("(<= p (q ?a) (not (foo ?a)))");
assert_eq!(reorder(desc.clone()), desc);
let desc = gdl::parse("(<= p (q ?a) (distinct ?a))");
assert_eq!(reorder(desc.clone()), desc);
} | identifier_body |
negative_literal_mover.rs | //! This module literals in a GDL description such that all variables in a negative literal (i.e. a
//! `distinct` or `not` literal) have been seen in positive literals occurring before that
//! `negative` literal. The resulting GDL should be semantically equivalent. To see why this is
//! necessary, see section 13.6 [... | (t: &Term) -> Vec<Variable> {
match t {
&VarTerm(ref v) => vec![(*v).clone()],
&FuncTerm(ref f) => {
let mut res = Vec::new();
for t in f.args.iter() {
res.extend(get_vars_from_term(t));
}
res
}
_ => Vec::new()
}
}
... | get_vars_from_term | identifier_name |
TestNextafter.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* | */
// Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh.
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
rs_allocation gAllocInTarget;
float __attribute__((kernel)) testNextafterFloatFloatFloat(float inV, unsigned int x) {
float inTarget = rsGetElementAt_flo... | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. | random_line_split |
timer.rs | use super::*;
use time;
use time::Tm;
/// A timer metric for tracking elapsed time
///
/// Internally uses a `Metric<i64>` with `Semantics::Instant` and `1` time dimension
pub struct Timer {
metric: Metric<i64>,
time_scale: Time,
start_time: Option<Tm>
}
/// Error encountered while starting or stopping a ... | (name: &str, time_scale: Time,
shorthelp_text: &str, longhelp_text: &str) -> Result<Self, String> {
let metric = Metric::new(
name,
0,
Semantics::Instant,
Unit::new().time(time_scale, 1)?,
shorthelp_text,
longhelp_text
)?;
... | new | identifier_name |
timer.rs | use super::*;
use time;
use time::Tm;
/// A timer metric for tracking elapsed time
///
/// Internally uses a `Metric<i64>` with `Semantics::Instant` and `1` time dimension
pub struct Timer {
metric: Metric<i64>,
time_scale: Time,
start_time: Option<Tm>
}
/// Error encountered while starting or stopping a ... |
timer.start().unwrap();
thread::sleep(Duration::from_secs(sleep_time));
let elapsed2 = timer.stop().unwrap();
assert_eq!(timer.elapsed(), elapsed1 + elapsed2);
}
| {
use super::super::Client;
use std::thread;
use std::time::Duration;
let mut timer = Timer::new("timer", Time::MSec, "", "").unwrap();
assert_eq!(timer.elapsed(), 0);
Client::new("timer_test").unwrap()
.export(&mut [&mut timer]).unwrap();
assert!(timer.stop().is_err());
... | identifier_body |
timer.rs | use super::*;
use time;
use time::Tm;
/// A timer metric for tracking elapsed time
///
/// Internally uses a `Metric<i64>` with `Semantics::Instant` and `1` time dimension
pub struct Timer {
metric: Metric<i64>,
time_scale: Time,
start_time: Option<Tm>
}
/// Error encountered while starting or stopping a ... | use std::thread;
use std::time::Duration;
let mut timer = Timer::new("timer", Time::MSec, "", "").unwrap();
assert_eq!(timer.elapsed(), 0);
Client::new("timer_test").unwrap()
.export(&mut [&mut timer]).unwrap();
assert!(timer.stop().is_err());
let sleep_time = 2; // seconds
... |
#[test]
pub fn test() {
use super::super::Client; | random_line_split |
nullable-pointer-iotareduction.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 ... | }
macro_rules! check_type {
($($a:tt)*) => {{
check_option!($($a)*);
check_fancy!($($a)*);
}}
}
pub fn main() {
check_type!(&17: &int);
check_type!(box 18: Box<int>);
check_type!(@19: @int);
check_type!("foo".to_owned(): ~str);
check_type!(vec!(20, 22): Vec<int> );
let ... | stringify!($T), stringify!($e))
}
}} | random_line_split |
nullable-pointer-iotareduction.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 ... | {
check_type!(&17: &int);
check_type!(box 18: Box<int>);
check_type!(@19: @int);
check_type!("foo".to_owned(): ~str);
check_type!(vec!(20, 22): Vec<int> );
let mint: uint = unsafe { cast::transmute(main) };
check_type!(main: fn(), |pthing| {
assert!(mint == unsafe { cast::transmute(*... | identifier_body | |
nullable-pointer-iotareduction.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 ... | <'r>(&'r self) -> (int, &'r T) {
match *self {
Nothing(..) => fail!("E::get_ref(Nothing::<{}>)", stringify!(T)),
Thing(x, ref y) => (x, y)
}
}
}
macro_rules! check_option {
($e:expr: $T:ty) => {{
check_option!($e: $T, |ptr| assert!(*ptr == $e));
}};
($e:... | get_ref | identifier_name |
tile.rs | use ndarray::{ArrayBase, DataMut, NdIndex, IntoDimension};
#[derive(Copy, Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Tile<D: ndarray::Dimension, I: NdIndex<D>> {
dim: D,
active: Option<(I, f64)>,
}
impl<D: ndarray::Dimen... |
fn scaled_addto<E: DataMut<Elem = f64>>(&self, alpha: f64, arr: &mut ArrayBase<E, Self::Dim>) {
if let Some((idx, activation)) = &self.active {
arr[idx.clone()] += alpha * activation;
}
}
}
impl<D, I> crate::params::BufferMut for Tile<D, I>
where
D: ndarray::Dimension,
I: ... | {
if let Some((idx, activation)) = &self.active {
arr[idx.clone()] += activation;
}
} | identifier_body |
tile.rs | use ndarray::{ArrayBase, DataMut, NdIndex, IntoDimension};
#[derive(Copy, Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Tile<D: ndarray::Dimension, I: NdIndex<D>> {
dim: D,
active: Option<(I, f64)>,
}
impl<D: ndarray::Dimen... |
fn scaled_addto<E: DataMut<Elem = f64>>(&self, alpha: f64, arr: &mut ArrayBase<E, Self::Dim>) {
if let Some((idx, activation)) = &self.active {
arr[idx.clone()] += alpha * activation;
}
}
}
impl<D, I> crate::params::BufferMut for Tile<D, I>
where
D: ndarray::Dimension,
I: N... | arr[idx.clone()] += activation;
}
} | random_line_split |
tile.rs | use ndarray::{ArrayBase, DataMut, NdIndex, IntoDimension};
#[derive(Copy, Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Tile<D: ndarray::Dimension, I: NdIndex<D>> {
dim: D,
active: Option<(I, f64)>,
}
impl<D: ndarray::Dimen... | (&mut self, other: &Self, f: impl Fn(f64, f64) -> f64) {
if self.dim!= other.dim {
panic!("Incompatible buffers shapes.")
}
match (&mut self.active, &other.active) {
(Some((i, x)), Some((j, y))) if i == j => *x = f(*x, *y),
_ => panic!("Incompatible buffer in... | merge_inplace | identifier_name |
htmllegendelement.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::HTMLLegendElementBinding;
use dom::bindings::codegen::Bindings::HTMLLegendEleme... | else {
el.check_disabled_attribute();
}
}
}
impl HTMLLegendElementMethods for HTMLLegendElement {
// https://html.spec.whatwg.org/multipage/#dom-legend-form
fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
let parent = self.upcast::<Node>().GetParentElement()?;
... | {
el.check_ancestors_disabled_state_for_form_control();
} | conditional_block |
htmllegendelement.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::HTMLLegendElementBinding;
use dom::bindings::codegen::Bindings::HTMLLegendEleme... | (&self, form: Option<&HTMLFormElement>) {
self.form_owner.set(form);
}
fn to_element<'a>(&'a self) -> &'a Element {
self.upcast::<Element>()
}
}
| set_form_owner | identifier_name |
htmllegendelement.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::HTMLLegendElementBinding;
use dom::bindings::codegen::Bindings::HTMLLegendEleme... | use dom::element::Element;
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{HTMLFormElement, FormControl};
use dom::node::{Node, UnbindContext};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom... | use dom::bindings::root::{DomRoot, MutNullableDom};
use dom::document::Document; | random_line_split |
htmllegendelement.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::HTMLLegendElementBinding;
use dom::bindings::codegen::Bindings::HTMLLegendEleme... |
}
impl HTMLLegendElementMethods for HTMLLegendElement {
// https://html.spec.whatwg.org/multipage/#dom-legend-form
fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
let parent = self.upcast::<Node>().GetParentElement()?;
if parent.is::<HTMLFieldSetElement>() {
return self.fo... | {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
... | identifier_body |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The context within which style is calculated.
use animation::Animation;
use app_units::Au;
use dom::OpaqueNod... |
/// Screen sized changed?
pub screen_size_changed: bool,
/// The CSS selector stylist.
pub stylist: Arc<Stylist>,
/// Starts at zero, and increased by one every time a layout completes.
/// This can be used to easily check for invalid stale data.
pub generation: u32,
/// Why is this ... | random_line_split | |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The context within which style is calculated.
use animation::Animation;
use app_units::Au;
use dom::OpaqueNod... | {
/// We're reflowing in order to send a display list to the screen.
ForDisplay,
/// We're reflowing in order to satisfy a script query. No display list will be created.
ForScriptQuery,
}
| ReflowGoal | identifier_name |
core.rs | // Core types.
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use std::os;
use std::path::Path;
use std::slice::SliceConcatExt;
use getopts;
use types::{Params, CommandCallback};
use types::{Options, Argument};
use formatting::HelpFormatter;
/// The command ... |
pub fn get_help(&self) -> String {
let mut formatter = self.make_formatter();
self.format_help(&mut formatter);
formatter.getvalue()
}
/// Returns the help option.
fn get_help_option(&self) -> Options {
let help_option_names = vec!["h", "help"];
let show_help =... | {
self.format_usage(formatter);
self.format_help_text(formatter);
self.format_options(formatter);
self.format_epilog(formatter);
} | identifier_body |
core.rs | // Core types.
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use std::os;
use std::path::Path;
use std::slice::SliceConcatExt;
use getopts;
use types::{Params, CommandCallback};
use types::{Options, Argument};
use formatting::HelpFormatter;
/// The command ... | (&self) -> getopts::Options {
let mut parser = getopts::Options::new();
for option in self.get_options().iter() {
option.add_to_parser(&mut parser);
}
return parser;
}
/// Create the parser and parses the arguments.
fn parse_args(&self, args: Vec<String>) -> Vec<... | make_parser | identifier_name |
core.rs | // Core types.
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use std::os;
use std::path::Path;
use std::slice::SliceConcatExt;
use getopts;
use types::{Params, CommandCallback};
use types::{Options, Argument};
use formatting::HelpFormatter;
/// The command ... | formatter.dedent();
}
}
fn format_options(&self, formatter: &mut HelpFormatter) {
let mut opts: Vec<(String, String)> = Vec::new();
for option in self.get_options().iter() {
opts.push(option.get_help_record());
}
if!opts.is_empty() {
f... | if !self.help.is_empty() {
formatter.write_paragraph();
formatter.indent();
formatter.write_text(self.help.clone()); | random_line_split |
core.rs | // Core types.
// Copyright (c) 2015 by Shipeng Feng.
// Licensed under the BSD License, see LICENSE for more details.
use std::os;
use std::path::Path;
use std::slice::SliceConcatExt;
use getopts;
use types::{Params, CommandCallback};
use types::{Options, Argument};
use formatting::HelpFormatter;
/// The command ... |
}
fn format_epilog(&self, formatter: &mut HelpFormatter) {
if!self.epilog.is_empty() {
formatter.write_paragraph();
formatter.indent();
formatter.write_text(self.epilog.clone());
formatter.dedent();
}
}
fn format_help(&self, formatter: &... | {
formatter.enter_section("Options");
formatter.write_dl(opts);
formatter.exit_section();
} | conditional_block |
bluetoothadvertisingdata.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::BluetoothAdvertisingDataBinding;
use dom::bindings::codegen::Bindings::Bluet... |
pub fn new(global: GlobalRef, appearance: u16, txPower: i8, rssi: i8) -> Root<BluetoothAdvertisingData> {
reflect_dom_object(box BluetoothAdvertisingData::new_inherited(appearance,
txPower,
... | {
BluetoothAdvertisingData {
reflector_: Reflector::new(),
appearance: appearance,
txPower: txPower,
rssi: rssi,
}
} | identifier_body |
bluetoothadvertisingdata.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::BluetoothAdvertisingDataBinding;
use dom::bindings::codegen::Bindings::Bluet... | }
} | random_line_split | |
bluetoothadvertisingdata.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::BluetoothAdvertisingDataBinding;
use dom::bindings::codegen::Bindings::Bluet... | (appearance: u16, txPower: i8, rssi: i8) -> BluetoothAdvertisingData {
BluetoothAdvertisingData {
reflector_: Reflector::new(),
appearance: appearance,
txPower: txPower,
rssi: rssi,
}
}
pub fn new(global: GlobalRef, appearance: u16, txPower: i8, r... | new_inherited | identifier_name |
number.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... |
}
DecodedNumber {
num: num,
octets_read: octets_read
}
}
#[cfg(test)]
mod tests {
use super::{encode, decode};
// slightly clumsy function to print the bits of a u8.
// it's useful even if it's bad :)
#[allow(unused)]
pub fn print_binary(octet: u8) {
let mut b... | {break;} | conditional_block |
number.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... | if num < (1 << n) - 1 {
return DecodedNumber {
num: num,
octets_read: 1
};
}
// We have read the prefix already, now count how many octets are in the rest list.
let mut octets_read = 1;
let mut m = 0;
while let Some(&octet) = octets.peek() {
n... | // octets must have length at least 1
// n must be between 1 and 8 inclusive
pub fn decode(octets: &mut Peekable<Iter<u8>>, n: u8) -> DecodedNumber {
// turn off bits which should not be checked.
let mut num = (*octets.next().unwrap() & (255 >> (8 - n))) as u32; | random_line_split |
number.rs | // Copyright 2017 ThetaSinner
//
// This file is part of Osmium.
// Osmium is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Osmi... | () {
let en = encode(42, 8);
assert_eq!(42, en.prefix);
assert!(en.rest.is_none());
}
#[test]
fn decode_starting_at_octet_boundary() {
let en = encode(42, 8);
let octets = vec!(en.prefix);
let dn = decode(&mut octets.iter().peekable(), 8);
assert_eq... | encode_starting_at_octet_boundary | identifier_name |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | (&self) -> Result<bool> {
trace!("Has category? '{}'", self.get_location());
self.get_header()
.read("category.value")
.context(anyhow!("Failed to read header at 'category.value' of '{}'", self.get_location()))
.map_err(Error::from)
.map(|x| x.is_some())
}... | has_category | identifier_name |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | let mut category = register
.get_category_by_name(s)?
.ok_or_else(|| anyhow!("Category does not exist"))?;
self.set_category(s)?;
self.add_link(&mut category)?;
Ok(())
}
fn get_category(&self) -> Result<String> {
trace!("Getting category from '{}'... | random_line_split | |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... |
fn has_category(&self) -> Result<bool> {
trace!("Has category? '{}'", self.get_location());
self.get_header()
.read("category.value")
.context(anyhow!("Failed to read header at 'category.value' of '{}'", self.get_location()))
.map_err(Error::from)
.map(|... | {
trace!("Getting category from '{}'", self.get_location());
self.get_header()
.read_string("category.value")?
.ok_or_else(|| anyhow!("Category name missing"))
} | identifier_body |
font_cache_thread.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 cssparser::SourceLocation;
use gfx::font_cache_thread::FontCacheThread;
use ipc_channel::ipc;
use style::compu... | () {
let (inp_chan, _) = ipc::channel().unwrap();
let (out_chan, out_receiver) = ipc::channel().unwrap();
let font_cache_thread = FontCacheThread::new(inp_chan, None);
let family_name = FamilyName {
name: From::from("test family"),
syntax: FamilyNameSyntax::Quoted,
};
let variant... | test_local_web_font | identifier_name |
font_cache_thread.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 cssparser::SourceLocation;
use gfx::font_cache_thread::FontCacheThread; | #[test]
fn test_local_web_font() {
let (inp_chan, _) = ipc::channel().unwrap();
let (out_chan, out_receiver) = ipc::channel().unwrap();
let font_cache_thread = FontCacheThread::new(inp_chan, None);
let family_name = FamilyName {
name: From::from("test family"),
syntax: FamilyNameSyntax::... | use ipc_channel::ipc;
use style::computed_values::font_family::{FamilyName, FamilyNameSyntax};
use style::font_face::{FontFaceRuleData, Source};
| random_line_split |
font_cache_thread.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 cssparser::SourceLocation;
use gfx::font_cache_thread::FontCacheThread;
use ipc_channel::ipc;
use style::compu... |
font_cache_thread.add_web_font(
family_name,
font_face_rule.font_face().unwrap().effective_sources(),
out_chan);
assert_eq!(out_receiver.recv().unwrap(), ());
}
| {
let (inp_chan, _) = ipc::channel().unwrap();
let (out_chan, out_receiver) = ipc::channel().unwrap();
let font_cache_thread = FontCacheThread::new(inp_chan, None);
let family_name = FamilyName {
name: From::from("test family"),
syntax: FamilyNameSyntax::Quoted,
};
let variant_na... | identifier_body |
x86_64.rs | #[repr(C)]
#[derive(Copy)]
pub struct lconv {
pub decimal_point: *mut ::char_t,
pub thousands_sep: *mut ::char_t,
pub grouping: *mut ::char_t,
pub int_curr_symbol: *mut ::char_t,
pub currency_symbol: *mut ::char_t,
pub mon_decimal_point: *mut ::char_t,
pub mon_thousands_sep: *mut ::char_t,
... | pub const LC_GLOBAL_LOCALE: locale_t = -1i64 as locale_t; | pub const LC_ALL_MASK: ::int_t = 8127;
| random_line_split |
x86_64.rs | #[repr(C)]
#[derive(Copy)]
pub struct | {
pub decimal_point: *mut ::char_t,
pub thousands_sep: *mut ::char_t,
pub grouping: *mut ::char_t,
pub int_curr_symbol: *mut ::char_t,
pub currency_symbol: *mut ::char_t,
pub mon_decimal_point: *mut ::char_t,
pub mon_thousands_sep: *mut ::char_t,
pub mon_grouping: *mut ::char_t,
pub... | lconv | identifier_name |
pointer.rs | use super::{AllocId, InterpResult};
use rustc_macros::HashStable;
use rustc_target::abi::{HasDataLayout, Size};
use std::convert::TryFrom;
use std::fmt;
////////////////////////////////////////////////////////////////////////////////
// Pointer arithmetic
/////////////////////////////////////////////////////////////... | <'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> {
let (res, over) = self.overflowing_signed_offset(val, i);
if over { throw_ub!(PointerArithOverflow) } else { Ok(res) }
}
}
impl<T: HasDataLayout> PointerArithmetic for T {}
/// This trait abstracts over the kind of provenance that is ass... | signed_offset | identifier_name |
pointer.rs | use super::{AllocId, InterpResult};
use rustc_macros::HashStable;
use rustc_target::abi::{HasDataLayout, Size};
use std::convert::TryFrom;
use std::fmt;
////////////////////////////////////////////////////////////////////////////////
// Pointer arithmetic
/////////////////////////////////////////////////////////////... |
fn get_alloc_id(self) -> AllocId {
self
}
}
/// Represents a pointer in the Miri engine.
///
/// Pointers are "tagged" with provenance information; typically the `AllocId` they belong to.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)]
#[derive(HashStable)]
pub ... | {
// Forward `alternate` flag to `alloc_id` printing.
if f.alternate() {
write!(f, "{:#?}", ptr.provenance)?;
} else {
write!(f, "{:?}", ptr.provenance)?;
}
// Print offset only if it is non-zero.
if ptr.offset.bytes() > 0 {
write!(f, "... | identifier_body |
pointer.rs | use super::{AllocId, InterpResult};
use rustc_macros::HashStable;
use rustc_target::abi::{HasDataLayout, Size};
use std::convert::TryFrom;
use std::fmt;
////////////////////////////////////////////////////////////////////////////////
// Pointer arithmetic
/////////////////////////////////////////////////////////////... | None => write!(f, "0x{:x}", self.offset.bytes()),
}
}
}
/// Produces a `Pointer` that points to the beginning of the `Allocation`.
impl From<AllocId> for Pointer {
#[inline(always)]
fn from(alloc_id: AllocId) -> Self {
Pointer::new(alloc_id, Size::ZERO)
}
}
impl<Tag> From<P... | match self.provenance {
Some(tag) => Provenance::fmt(&Pointer::new(tag, self.offset), f), | random_line_split |
pointer.rs | use super::{AllocId, InterpResult};
use rustc_macros::HashStable;
use rustc_target::abi::{HasDataLayout, Size};
use std::convert::TryFrom;
use std::fmt;
////////////////////////////////////////////////////////////////////////////////
// Pointer arithmetic
/////////////////////////////////////////////////////////////... | else {
let res = val.overflowing_sub(n);
let (val, over) = self.truncate_to_ptr(res);
(val, over || i < self.machine_isize_min())
}
}
#[inline]
fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> {
let (res, over) = self.overflowing_offse... | {
let (val, over) = self.overflowing_offset(val, n);
(val, over || i > self.machine_isize_max())
} | conditional_block |
mod.rs | mod test_signal;
// NOTE: DragonFly lacks a kernel-level implementation of Posix AIO as of
// this writing. There is an user-level implementation, but whether aio
// works or not heavily depends on which pthread implementation is chosen
// by the user at link time. For this reason we do not want to run aio test | target_os = "netbsd"))]
mod test_aio;
#[cfg(target_os = "linux")]
mod test_signalfd;
mod test_socket;
mod test_sockopt;
mod test_select;
#[cfg(any(target_os = "android", target_os = "linux"))]
mod test_sysinfo;
mod test_termios;
mod test_ioctl;
mod test_wait;
mod test_uio;
#[cfg(target_os = "linux")]
mod tes... | // cases on DragonFly.
#[cfg(any(target_os = "freebsd",
target_os = "ios",
target_os = "linux",
target_os = "macos", | random_line_split |
mod.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <A, T, F>(addr: A, mut action: F) -> IoResult<T> where
A: ToSocketAddr,
F: FnMut(SocketAddr) -> IoResult<T>,
{
const DEFAULT_ERROR: IoError = IoError {
kind: InvalidInput,
desc: "no addresses found for hostname",
detail: None
};
let addresses = try!(addr.to_socket_addr_all()... | with_addresses | identifier_name |
mod.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 ... | {
const DEFAULT_ERROR: IoError = IoError {
kind: InvalidInput,
desc: "no addresses found for hostname",
detail: None
};
let addresses = try!(addr.to_socket_addr_all());
let mut err = DEFAULT_ERROR;
for addr in addresses {
match action(addr) {
Ok(r) => ret... | identifier_body | |
mod.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 ... | detail: None
};
let addresses = try!(addr.to_socket_addr_all());
let mut err = DEFAULT_ERROR;
for addr in addresses {
match action(addr) {
Ok(r) => return Ok(r),
Err(e) => err = e
}
}
Err(err)
} | kind: InvalidInput,
desc: "no addresses found for hostname", | random_line_split |
mod.rs |
sockaddr_in,
sockaddr_in6,
sockaddr_un,
sa_family_t,
};
pub use self::multicast::{
ip_mreq,
ipv6_mreq,
};
pub use self::consts::*;
pub use libc::sockaddr_storage;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(i32)]
pub enum SockType {
Stream = consts::SOCK_STREAM,
Datagram = co... | <'a>(&'a [u8]);
impl<'a> Iterator for CmsgIterator<'a> {
type Item = ControlMessage<'a>;
// The implementation loosely follows CMSG_FIRSTHDR / CMSG_NXTHDR,
// although we handle the invariants in slightly different places to
// get a better iterator interface.
fn next(&mut self) -> Option<ControlM... | CmsgIterator | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.