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 |
---|---|---|---|---|
box.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-android: FIXME(#10381)
// compile-flags:-Z extra-debug-info
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print *a
// check:$1 = 1
// debugger:print *b
// check:$2 = {2, 3.5}
// debugger:print c->val
// check:$3 = 4
// debugger:print d->val
// check:$4 = false
#[feature(managed_boxes)];
#[allow(unused_variable)];
fn
|
() {
let a = ~1;
let b = ~(2, 3.5);
let c = @4;
let d = @false;
_zzz();
}
fn _zzz() {()}
|
main
|
identifier_name
|
enum-alignment.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
use std::ptr;
use std::sys;
fn
|
<T>(ptr: &T) -> uint {
let ptr = ptr::to_unsafe_ptr(ptr);
ptr as uint
}
fn is_aligned<T>(ptr: &T) -> bool {
unsafe {
let addr: uint = cast::transmute(ptr);
(addr % sys::min_align_of::<T>()) == 0
}
}
pub fn main() {
let x = Some(0u64);
match x {
None => fail2!(),
Some(ref y) => assert!(is_aligned(y))
}
}
|
addr_of
|
identifier_name
|
enum-alignment.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
use std::ptr;
use std::sys;
fn addr_of<T>(ptr: &T) -> uint
|
fn is_aligned<T>(ptr: &T) -> bool {
unsafe {
let addr: uint = cast::transmute(ptr);
(addr % sys::min_align_of::<T>()) == 0
}
}
pub fn main() {
let x = Some(0u64);
match x {
None => fail2!(),
Some(ref y) => assert!(is_aligned(y))
}
}
|
{
let ptr = ptr::to_unsafe_ptr(ptr);
ptr as uint
}
|
identifier_body
|
enum-alignment.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
use std::ptr;
use std::sys;
fn addr_of<T>(ptr: &T) -> uint {
let ptr = ptr::to_unsafe_ptr(ptr);
ptr as uint
}
fn is_aligned<T>(ptr: &T) -> bool {
unsafe {
let addr: uint = cast::transmute(ptr);
(addr % sys::min_align_of::<T>()) == 0
}
}
pub fn main() {
|
None => fail2!(),
Some(ref y) => assert!(is_aligned(y))
}
}
|
let x = Some(0u64);
match x {
|
random_line_split
|
io.rs
|
/*!
This module provides some miscellaneous IO support routines.
*/
use std::io::{IoError, IoResult, OtherIoError};
/**
Reads a line of input from the given `Reader`. This does not require a push-back buffer. It returns the line *with* the line terminator.
Note that this function *does not* support old-school Mac OS newlines (i.e. a single carriage return). If it encounters a carriage return which is *not* immediately followed by a line feed, the carriage return will be included as part of the line.
*/
pub fn read_line<R: Reader>(r: &mut R) -> IoResult<String> {
let mut line = String::new();
loop {
match read_utf8_char(r) {
Ok('\n') => {
line.push('\n');
break;
},
Ok(c) => {
line.push(c);
}
Err(err) => {
if err.kind == ::std::io::EndOfFile && line.len() > 0 {
break
} else {
return Err(err)
}
}
}
}
Ok(line)
}
#[test]
fn test_read_line() {
use std::borrow::ToOwned;
let s = "line one\nline two\r\nline three\n";
let mut r = ::std::io::BufReader::new(s.as_bytes());
let oks = |s:&str| Ok(s.to_owned());
assert_eq!(read_line(&mut r), oks("line one\n"));
assert_eq!(read_line(&mut r), oks("line two\r\n"));
assert_eq!(read_line(&mut r), oks("line three\n"));
}
/**
Reads a single UTF-8 encoded Unicode code point from a `Reader`.
*/
pub fn read_utf8_char<R: Reader>(r: &mut R) -> IoResult<char> {
fn invalid_utf8<T>(b: u8, initial: bool) -> IoResult<T> {
Err(IoError {
kind: OtherIoError,
desc: "invalid utf-8 sequence",
detail: if initial {
Some(format!("invalid initial code unit {:#02x}", b))
} else {
Some(format!("invalid continuation code unit {:#02x}", b))
}
})
}
fn invalid_cp<T>(cp: u32) -> IoResult<T> {
Err(IoError {
kind: OtherIoError,
desc: "invalid Unicode code point",
detail: Some(format!("invalid code point {:#08x}", cp))
})
}
// Why not use std::str::utf8_char_width? We need to know the encoding to mask away the size bits anyway.
let (mut cp, n) = match try!(r.read_u8()) {
b @ 0b0000_0000... 0b0111_1111 => (b as u32, 0),
b @ 0b1100_0000... 0b1101_1111 => ((b & 0b0001_1111) as u32, 1),
b @ 0b1110_0000... 0b1110_1111 => ((b & 0b0000_1111) as u32, 2),
b @ 0b1111_0000... 0b1111_0111 => ((b & 0b0000_0111) as u32, 3),
b @ 0b1111_1000... 0b1111_1011 => ((b & 0b0000_0011) as u32, 4),
b @ 0b1111_1100... 0b1111_1101 => ((b & 0b0000_0001) as u32, 5),
b => return invalid_utf8(b, true)
};
for _ in range(0u, n) {
let b = match try!(r.read_u8()) {
b @ 0b10_000000... 0b10_111111 => (b & 0b00_111111) as u32,
b => return invalid_utf8(b, false)
};
cp = (cp << 6) | b;
}
::std::char::from_u32(cp)
.map(|c| Ok(c))
.unwrap_or_else(|| invalid_cp(cp))
}
#[test]
fn test_read_utf8_char() {
fn test_str(s: &str) {
let mut reader = ::std::io::BufReader::new(s.as_bytes());
for c in s.chars() {
assert_eq!(Ok(c), read_utf8_char(&mut reader))
}
}
fn
|
(s: &[u8]) -> IoResult<char> {
let mut reader = ::std::io::BufReader::new(s);
read_utf8_char(&mut reader)
}
test_str("abcdef");
test_str("私の日本語わ下手ですよ!");
assert!(first(&[0b1000_0000u8]).is_err());
assert!(first(&[0b1100_0000u8, 0b0000_0000]).is_err());
}
/**
Reads a single line from standard input.
*/
pub fn stdin_read_line() -> IoResult<String> {
read_line(&mut ::std::io::stdio::stdin_raw())
}
|
first
|
identifier_name
|
io.rs
|
/*!
This module provides some miscellaneous IO support routines.
*/
use std::io::{IoError, IoResult, OtherIoError};
/**
Reads a line of input from the given `Reader`. This does not require a push-back buffer. It returns the line *with* the line terminator.
Note that this function *does not* support old-school Mac OS newlines (i.e. a single carriage return). If it encounters a carriage return which is *not* immediately followed by a line feed, the carriage return will be included as part of the line.
*/
pub fn read_line<R: Reader>(r: &mut R) -> IoResult<String> {
let mut line = String::new();
loop {
match read_utf8_char(r) {
Ok('\n') => {
line.push('\n');
break;
},
Ok(c) => {
line.push(c);
}
Err(err) => {
if err.kind == ::std::io::EndOfFile && line.len() > 0 {
break
} else {
return Err(err)
}
}
}
}
Ok(line)
}
#[test]
fn test_read_line() {
use std::borrow::ToOwned;
let s = "line one\nline two\r\nline three\n";
let mut r = ::std::io::BufReader::new(s.as_bytes());
let oks = |s:&str| Ok(s.to_owned());
assert_eq!(read_line(&mut r), oks("line one\n"));
assert_eq!(read_line(&mut r), oks("line two\r\n"));
assert_eq!(read_line(&mut r), oks("line three\n"));
}
/**
Reads a single UTF-8 encoded Unicode code point from a `Reader`.
*/
pub fn read_utf8_char<R: Reader>(r: &mut R) -> IoResult<char> {
fn invalid_utf8<T>(b: u8, initial: bool) -> IoResult<T> {
Err(IoError {
kind: OtherIoError,
desc: "invalid utf-8 sequence",
detail: if initial {
Some(format!("invalid initial code unit {:#02x}", b))
} else {
Some(format!("invalid continuation code unit {:#02x}", b))
}
})
}
fn invalid_cp<T>(cp: u32) -> IoResult<T> {
Err(IoError {
kind: OtherIoError,
desc: "invalid Unicode code point",
detail: Some(format!("invalid code point {:#08x}", cp))
})
}
// Why not use std::str::utf8_char_width? We need to know the encoding to mask away the size bits anyway.
let (mut cp, n) = match try!(r.read_u8()) {
b @ 0b0000_0000... 0b0111_1111 => (b as u32, 0),
b @ 0b1100_0000... 0b1101_1111 => ((b & 0b0001_1111) as u32, 1),
b @ 0b1110_0000... 0b1110_1111 => ((b & 0b0000_1111) as u32, 2),
b @ 0b1111_0000... 0b1111_0111 => ((b & 0b0000_0111) as u32, 3),
b @ 0b1111_1000... 0b1111_1011 => ((b & 0b0000_0011) as u32, 4),
b @ 0b1111_1100... 0b1111_1101 => ((b & 0b0000_0001) as u32, 5),
b => return invalid_utf8(b, true)
};
for _ in range(0u, n) {
let b = match try!(r.read_u8()) {
b @ 0b10_000000... 0b10_111111 => (b & 0b00_111111) as u32,
b => return invalid_utf8(b, false)
};
cp = (cp << 6) | b;
}
::std::char::from_u32(cp)
.map(|c| Ok(c))
.unwrap_or_else(|| invalid_cp(cp))
}
#[test]
fn test_read_utf8_char() {
fn test_str(s: &str) {
let mut reader = ::std::io::BufReader::new(s.as_bytes());
for c in s.chars() {
assert_eq!(Ok(c), read_utf8_char(&mut reader))
}
}
fn first(s: &[u8]) -> IoResult<char> {
let mut reader = ::std::io::BufReader::new(s);
read_utf8_char(&mut reader)
}
test_str("abcdef");
test_str("私の日本語わ下手ですよ!");
assert!(first(&[0b1000_0000u8]).is_err());
assert!(first(&[0b1100_0000u8, 0b0000_0000]).is_err());
}
/**
Reads a single line from standard input.
*/
pub fn stdin_read_line() -> IoResult<String> {
read_line(&mut ::std::io::stdio::stdin_raw())
|
}
|
random_line_split
|
|
io.rs
|
/*!
This module provides some miscellaneous IO support routines.
*/
use std::io::{IoError, IoResult, OtherIoError};
/**
Reads a line of input from the given `Reader`. This does not require a push-back buffer. It returns the line *with* the line terminator.
Note that this function *does not* support old-school Mac OS newlines (i.e. a single carriage return). If it encounters a carriage return which is *not* immediately followed by a line feed, the carriage return will be included as part of the line.
*/
pub fn read_line<R: Reader>(r: &mut R) -> IoResult<String> {
let mut line = String::new();
loop {
match read_utf8_char(r) {
Ok('\n') => {
line.push('\n');
break;
},
Ok(c) => {
line.push(c);
}
Err(err) => {
if err.kind == ::std::io::EndOfFile && line.len() > 0 {
break
} else {
return Err(err)
}
}
}
}
Ok(line)
}
#[test]
fn test_read_line() {
use std::borrow::ToOwned;
let s = "line one\nline two\r\nline three\n";
let mut r = ::std::io::BufReader::new(s.as_bytes());
let oks = |s:&str| Ok(s.to_owned());
assert_eq!(read_line(&mut r), oks("line one\n"));
assert_eq!(read_line(&mut r), oks("line two\r\n"));
assert_eq!(read_line(&mut r), oks("line three\n"));
}
/**
Reads a single UTF-8 encoded Unicode code point from a `Reader`.
*/
pub fn read_utf8_char<R: Reader>(r: &mut R) -> IoResult<char> {
fn invalid_utf8<T>(b: u8, initial: bool) -> IoResult<T> {
Err(IoError {
kind: OtherIoError,
desc: "invalid utf-8 sequence",
detail: if initial {
Some(format!("invalid initial code unit {:#02x}", b))
} else {
Some(format!("invalid continuation code unit {:#02x}", b))
}
})
}
fn invalid_cp<T>(cp: u32) -> IoResult<T> {
Err(IoError {
kind: OtherIoError,
desc: "invalid Unicode code point",
detail: Some(format!("invalid code point {:#08x}", cp))
})
}
// Why not use std::str::utf8_char_width? We need to know the encoding to mask away the size bits anyway.
let (mut cp, n) = match try!(r.read_u8()) {
b @ 0b0000_0000... 0b0111_1111 => (b as u32, 0),
b @ 0b1100_0000... 0b1101_1111 => ((b & 0b0001_1111) as u32, 1),
b @ 0b1110_0000... 0b1110_1111 => ((b & 0b0000_1111) as u32, 2),
b @ 0b1111_0000... 0b1111_0111 => ((b & 0b0000_0111) as u32, 3),
b @ 0b1111_1000... 0b1111_1011 => ((b & 0b0000_0011) as u32, 4),
b @ 0b1111_1100... 0b1111_1101 => ((b & 0b0000_0001) as u32, 5),
b => return invalid_utf8(b, true)
};
for _ in range(0u, n) {
let b = match try!(r.read_u8()) {
b @ 0b10_000000... 0b10_111111 => (b & 0b00_111111) as u32,
b => return invalid_utf8(b, false)
};
cp = (cp << 6) | b;
}
::std::char::from_u32(cp)
.map(|c| Ok(c))
.unwrap_or_else(|| invalid_cp(cp))
}
#[test]
fn test_read_utf8_char() {
fn test_str(s: &str) {
let mut reader = ::std::io::BufReader::new(s.as_bytes());
for c in s.chars() {
assert_eq!(Ok(c), read_utf8_char(&mut reader))
}
}
fn first(s: &[u8]) -> IoResult<char> {
let mut reader = ::std::io::BufReader::new(s);
read_utf8_char(&mut reader)
}
test_str("abcdef");
test_str("私の日本語わ下手ですよ!");
assert!(first(&[0b1000_0000u8]).is_err());
assert!(first(&[0b1100_0000u8, 0b0000_0000]).is_err());
}
/**
Reads a single line from standard input.
*/
pub fn stdin_read_line() -> IoResult<String> {
read_line(&mut ::std:
|
:io::stdio::stdin_raw())
}
|
identifier_body
|
|
builder.rs
|
use ecs::state::State;
use ecs::state::update_queue::UpdateQueues;
use ecs::group::Groups;
use ecs::module::{Module, Modules,Component};
pub struct StateBuilder<Cx: Send> {
update_queues: UpdateQueues,
groups: Groups,
modules: Modules<Cx>,
}
impl<Cx: Send> StateBuilder<Cx> {
pub fn new() -> Self {
StateBuilder {
update_queues: UpdateQueues::new(),
groups: Groups::new(),
modules: Modules::new(),
}
}
|
self.update_queues.register::<C>();
self
}
pub fn register_module<M: Module<Cx>>(&mut self, module: M) -> &mut Self {
self.modules.insert(Box::new(module));
self
}
pub fn build(self) -> State<Cx> {
State::new(self.modules,
self.groups,
self.update_queues)
}
}
|
pub fn register_component<C: Component>(&mut self) -> &mut Self {
|
random_line_split
|
builder.rs
|
use ecs::state::State;
use ecs::state::update_queue::UpdateQueues;
use ecs::group::Groups;
use ecs::module::{Module, Modules,Component};
pub struct StateBuilder<Cx: Send> {
update_queues: UpdateQueues,
groups: Groups,
modules: Modules<Cx>,
}
impl<Cx: Send> StateBuilder<Cx> {
pub fn new() -> Self
|
pub fn register_component<C: Component>(&mut self) -> &mut Self {
self.update_queues.register::<C>();
self
}
pub fn register_module<M: Module<Cx>>(&mut self, module: M) -> &mut Self {
self.modules.insert(Box::new(module));
self
}
pub fn build(self) -> State<Cx> {
State::new(self.modules,
self.groups,
self.update_queues)
}
}
|
{
StateBuilder {
update_queues: UpdateQueues::new(),
groups: Groups::new(),
modules: Modules::new(),
}
}
|
identifier_body
|
builder.rs
|
use ecs::state::State;
use ecs::state::update_queue::UpdateQueues;
use ecs::group::Groups;
use ecs::module::{Module, Modules,Component};
pub struct StateBuilder<Cx: Send> {
update_queues: UpdateQueues,
groups: Groups,
modules: Modules<Cx>,
}
impl<Cx: Send> StateBuilder<Cx> {
pub fn new() -> Self {
StateBuilder {
update_queues: UpdateQueues::new(),
groups: Groups::new(),
modules: Modules::new(),
}
}
pub fn
|
<C: Component>(&mut self) -> &mut Self {
self.update_queues.register::<C>();
self
}
pub fn register_module<M: Module<Cx>>(&mut self, module: M) -> &mut Self {
self.modules.insert(Box::new(module));
self
}
pub fn build(self) -> State<Cx> {
State::new(self.modules,
self.groups,
self.update_queues)
}
}
|
register_component
|
identifier_name
|
angle.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/. */
//! Computed angles.
use num_traits::Zero;
use std::{f32, f64};
use std::f64::consts::PI;
use std::ops::Add;
use values::CSSFloat;
use values::animated::{Animate, Procedure};
use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// A computed angle.
#[animate(fallback = "Self::animate_fallback")]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss)]
#[derive(PartialOrd, ToAnimatedZero)]
pub enum Angle {
/// An angle with degree unit.
#[css(dimension)]
Deg(CSSFloat),
/// An angle with gradian unit.
#[css(dimension)]
Grad(CSSFloat),
/// An angle with radian unit.
#[css(dimension)]
Rad(CSSFloat),
/// An angle with turn unit.
#[css(dimension)]
Turn(CSSFloat),
}
impl Angle {
/// Creates a computed `Angle` value from a radian amount.
pub fn from_radians(radians: CSSFloat) -> Self {
Angle::Rad(radians)
}
/// Returns the amount of radians this angle represents.
#[inline]
pub fn radians(&self) -> CSSFloat {
self.radians64().min(f32::MAX as f64).max(f32::MIN as f64) as f32
}
/// Returns the amount of radians this angle represents as a `f64`.
///
/// Gecko stores angles as singles, but does this computation using doubles.
/// See nsCSSValue::GetAngleValueInRadians.
/// This is significant enough to mess up rounding to the nearest
/// quarter-turn for 225 degrees, for example.
#[inline]
pub fn radians64(&self) -> f64 {
const RAD_PER_DEG: f64 = PI / 180.0;
const RAD_PER_GRAD: f64 = PI / 200.0;
const RAD_PER_TURN: f64 = PI * 2.0;
let radians = match *self {
Angle::Deg(val) => val as f64 * RAD_PER_DEG,
Angle::Grad(val) => val as f64 * RAD_PER_GRAD,
Angle::Turn(val) => val as f64 * RAD_PER_TURN,
Angle::Rad(val) => val as f64,
};
radians.min(f64::MAX).max(f64::MIN)
}
/// <https://drafts.csswg.org/css-transitions/#animtype-number>
#[inline]
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
Ok(Angle::from_radians(self.radians().animate(&other.radians(), procedure)?))
}
}
impl AsRef<Angle> for Angle {
#[inline]
fn as_ref(&self) -> &Self {
self
}
}
impl Add for Angle {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
match (self, rhs) {
(Angle::Deg(x), Angle::Deg(y)) => Angle::Deg(x + y),
(Angle::Grad(x), Angle::Grad(y)) => Angle::Grad(x + y),
(Angle::Turn(x), Angle::Turn(y)) => Angle::Turn(x + y),
(Angle::Rad(x), Angle::Rad(y)) => Angle::Rad(x + y),
_ => Angle::from_radians(self.radians() + rhs.radians()),
}
}
}
impl Zero for Angle {
#[inline]
fn zero() -> Self {
Angle::from_radians(0.0)
}
#[inline]
fn is_zero(&self) -> bool {
match *self {
Angle::Deg(val) |
|
Angle::Grad(val) |
Angle::Turn(val) |
Angle::Rad(val) => val == 0.
}
}
}
impl ComputeSquaredDistance for Angle {
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
// Use the formula for calculating the distance between angles defined in SVG:
// https://www.w3.org/TR/SVG/animate.html#complexDistances
self.radians64().compute_squared_distance(&other.radians64())
}
}
|
random_line_split
|
|
angle.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/. */
//! Computed angles.
use num_traits::Zero;
use std::{f32, f64};
use std::f64::consts::PI;
use std::ops::Add;
use values::CSSFloat;
use values::animated::{Animate, Procedure};
use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// A computed angle.
#[animate(fallback = "Self::animate_fallback")]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss)]
#[derive(PartialOrd, ToAnimatedZero)]
pub enum Angle {
/// An angle with degree unit.
#[css(dimension)]
Deg(CSSFloat),
/// An angle with gradian unit.
#[css(dimension)]
Grad(CSSFloat),
/// An angle with radian unit.
#[css(dimension)]
Rad(CSSFloat),
/// An angle with turn unit.
#[css(dimension)]
Turn(CSSFloat),
}
impl Angle {
/// Creates a computed `Angle` value from a radian amount.
pub fn from_radians(radians: CSSFloat) -> Self {
Angle::Rad(radians)
}
/// Returns the amount of radians this angle represents.
#[inline]
pub fn radians(&self) -> CSSFloat {
self.radians64().min(f32::MAX as f64).max(f32::MIN as f64) as f32
}
/// Returns the amount of radians this angle represents as a `f64`.
///
/// Gecko stores angles as singles, but does this computation using doubles.
/// See nsCSSValue::GetAngleValueInRadians.
/// This is significant enough to mess up rounding to the nearest
/// quarter-turn for 225 degrees, for example.
#[inline]
pub fn radians64(&self) -> f64 {
const RAD_PER_DEG: f64 = PI / 180.0;
const RAD_PER_GRAD: f64 = PI / 200.0;
const RAD_PER_TURN: f64 = PI * 2.0;
let radians = match *self {
Angle::Deg(val) => val as f64 * RAD_PER_DEG,
Angle::Grad(val) => val as f64 * RAD_PER_GRAD,
Angle::Turn(val) => val as f64 * RAD_PER_TURN,
Angle::Rad(val) => val as f64,
};
radians.min(f64::MAX).max(f64::MIN)
}
/// <https://drafts.csswg.org/css-transitions/#animtype-number>
#[inline]
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
Ok(Angle::from_radians(self.radians().animate(&other.radians(), procedure)?))
}
}
impl AsRef<Angle> for Angle {
#[inline]
fn as_ref(&self) -> &Self {
self
}
}
impl Add for Angle {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
match (self, rhs) {
(Angle::Deg(x), Angle::Deg(y)) => Angle::Deg(x + y),
(Angle::Grad(x), Angle::Grad(y)) => Angle::Grad(x + y),
(Angle::Turn(x), Angle::Turn(y)) => Angle::Turn(x + y),
(Angle::Rad(x), Angle::Rad(y)) => Angle::Rad(x + y),
_ => Angle::from_radians(self.radians() + rhs.radians()),
}
}
}
impl Zero for Angle {
#[inline]
fn zero() -> Self {
Angle::from_radians(0.0)
}
#[inline]
fn is_zero(&self) -> bool {
match *self {
Angle::Deg(val) |
Angle::Grad(val) |
Angle::Turn(val) |
Angle::Rad(val) => val == 0.
}
}
}
impl ComputeSquaredDistance for Angle {
#[inline]
fn
|
(&self, other: &Self) -> Result<SquaredDistance, ()> {
// Use the formula for calculating the distance between angles defined in SVG:
// https://www.w3.org/TR/SVG/animate.html#complexDistances
self.radians64().compute_squared_distance(&other.radians64())
}
}
|
compute_squared_distance
|
identifier_name
|
angle.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/. */
//! Computed angles.
use num_traits::Zero;
use std::{f32, f64};
use std::f64::consts::PI;
use std::ops::Add;
use values::CSSFloat;
use values::animated::{Animate, Procedure};
use values::distance::{ComputeSquaredDistance, SquaredDistance};
/// A computed angle.
#[animate(fallback = "Self::animate_fallback")]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(Animate, Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss)]
#[derive(PartialOrd, ToAnimatedZero)]
pub enum Angle {
/// An angle with degree unit.
#[css(dimension)]
Deg(CSSFloat),
/// An angle with gradian unit.
#[css(dimension)]
Grad(CSSFloat),
/// An angle with radian unit.
#[css(dimension)]
Rad(CSSFloat),
/// An angle with turn unit.
#[css(dimension)]
Turn(CSSFloat),
}
impl Angle {
/// Creates a computed `Angle` value from a radian amount.
pub fn from_radians(radians: CSSFloat) -> Self {
Angle::Rad(radians)
}
/// Returns the amount of radians this angle represents.
#[inline]
pub fn radians(&self) -> CSSFloat {
self.radians64().min(f32::MAX as f64).max(f32::MIN as f64) as f32
}
/// Returns the amount of radians this angle represents as a `f64`.
///
/// Gecko stores angles as singles, but does this computation using doubles.
/// See nsCSSValue::GetAngleValueInRadians.
/// This is significant enough to mess up rounding to the nearest
/// quarter-turn for 225 degrees, for example.
#[inline]
pub fn radians64(&self) -> f64 {
const RAD_PER_DEG: f64 = PI / 180.0;
const RAD_PER_GRAD: f64 = PI / 200.0;
const RAD_PER_TURN: f64 = PI * 2.0;
let radians = match *self {
Angle::Deg(val) => val as f64 * RAD_PER_DEG,
Angle::Grad(val) => val as f64 * RAD_PER_GRAD,
Angle::Turn(val) => val as f64 * RAD_PER_TURN,
Angle::Rad(val) => val as f64,
};
radians.min(f64::MAX).max(f64::MIN)
}
/// <https://drafts.csswg.org/css-transitions/#animtype-number>
#[inline]
fn animate_fallback(&self, other: &Self, procedure: Procedure) -> Result<Self, ()> {
Ok(Angle::from_radians(self.radians().animate(&other.radians(), procedure)?))
}
}
impl AsRef<Angle> for Angle {
#[inline]
fn as_ref(&self) -> &Self
|
}
impl Add for Angle {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
match (self, rhs) {
(Angle::Deg(x), Angle::Deg(y)) => Angle::Deg(x + y),
(Angle::Grad(x), Angle::Grad(y)) => Angle::Grad(x + y),
(Angle::Turn(x), Angle::Turn(y)) => Angle::Turn(x + y),
(Angle::Rad(x), Angle::Rad(y)) => Angle::Rad(x + y),
_ => Angle::from_radians(self.radians() + rhs.radians()),
}
}
}
impl Zero for Angle {
#[inline]
fn zero() -> Self {
Angle::from_radians(0.0)
}
#[inline]
fn is_zero(&self) -> bool {
match *self {
Angle::Deg(val) |
Angle::Grad(val) |
Angle::Turn(val) |
Angle::Rad(val) => val == 0.
}
}
}
impl ComputeSquaredDistance for Angle {
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<SquaredDistance, ()> {
// Use the formula for calculating the distance between angles defined in SVG:
// https://www.w3.org/TR/SVG/animate.html#complexDistances
self.radians64().compute_squared_distance(&other.radians64())
}
}
|
{
self
}
|
identifier_body
|
FWTCBFbC.rs
|
pub fn count_characters(words: Vec<String>, chars: String) -> i32 {
use std::collections::{HashMap, HashSet};
let char_set = {
let mut char_table = HashMap::new();
for c in chars.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
};
let words_sets = words
.iter()
.map(|w| {
let mut char_table = HashMap::new();
for c in w.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
})
.collect::<Vec<_>>();
dbg!(&char_set);
dbg!(&words_sets);
let mut result = 0;
for i in 0..words_sets.len() {
if words[i].len() > chars.len() {
continue;
}
let mut flag = true;
for (k, v) in &words_sets[i] {
if let Some(n) = char_set.get(k) {
if n < v {
flag = false;
break;
}
} else {
flag = false;
break;
}
}
if flag {
result += words[i].len()
}
}
result as i32
}
fn main()
|
{
dbg!(count_characters(
vec![
"cat".to_string(),
"bt".to_string(),
"hat".to_string(),
"tree".to_string()
],
"atach".to_string()
));
dbg!(count_characters(
vec![
"hello".to_string(),
"world".to_string(),
"leetcode".to_string(),
],
"welldonehoneyr".to_string()
));
}
|
identifier_body
|
|
FWTCBFbC.rs
|
pub fn count_characters(words: Vec<String>, chars: String) -> i32 {
use std::collections::{HashMap, HashSet};
let char_set = {
let mut char_table = HashMap::new();
for c in chars.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
};
let words_sets = words
.iter()
.map(|w| {
let mut char_table = HashMap::new();
for c in w.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
})
.collect::<Vec<_>>();
dbg!(&char_set);
dbg!(&words_sets);
let mut result = 0;
for i in 0..words_sets.len() {
if words[i].len() > chars.len() {
continue;
}
let mut flag = true;
for (k, v) in &words_sets[i] {
if let Some(n) = char_set.get(k) {
if n < v {
flag = false;
break;
}
} else {
flag = false;
break;
}
}
if flag {
result += words[i].len()
}
}
result as i32
}
fn main() {
dbg!(count_characters(
vec![
"cat".to_string(),
"bt".to_string(),
"hat".to_string(),
"tree".to_string()
],
"atach".to_string()
));
dbg!(count_characters(
|
"welldonehoneyr".to_string()
));
}
|
vec![
"hello".to_string(),
"world".to_string(),
"leetcode".to_string(),
],
|
random_line_split
|
FWTCBFbC.rs
|
pub fn count_characters(words: Vec<String>, chars: String) -> i32 {
use std::collections::{HashMap, HashSet};
let char_set = {
let mut char_table = HashMap::new();
for c in chars.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
};
let words_sets = words
.iter()
.map(|w| {
let mut char_table = HashMap::new();
for c in w.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
})
.collect::<Vec<_>>();
dbg!(&char_set);
dbg!(&words_sets);
let mut result = 0;
for i in 0..words_sets.len() {
if words[i].len() > chars.len() {
continue;
}
let mut flag = true;
for (k, v) in &words_sets[i] {
if let Some(n) = char_set.get(k) {
if n < v {
flag = false;
break;
}
} else {
flag = false;
break;
}
}
if flag {
result += words[i].len()
}
}
result as i32
}
fn
|
() {
dbg!(count_characters(
vec![
"cat".to_string(),
"bt".to_string(),
"hat".to_string(),
"tree".to_string()
],
"atach".to_string()
));
dbg!(count_characters(
vec![
"hello".to_string(),
"world".to_string(),
"leetcode".to_string(),
],
"welldonehoneyr".to_string()
));
}
|
main
|
identifier_name
|
FWTCBFbC.rs
|
pub fn count_characters(words: Vec<String>, chars: String) -> i32 {
use std::collections::{HashMap, HashSet};
let char_set = {
let mut char_table = HashMap::new();
for c in chars.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
};
let words_sets = words
.iter()
.map(|w| {
let mut char_table = HashMap::new();
for c in w.chars() {
*char_table.entry(c).or_insert(0) += 1
}
char_table
})
.collect::<Vec<_>>();
dbg!(&char_set);
dbg!(&words_sets);
let mut result = 0;
for i in 0..words_sets.len() {
if words[i].len() > chars.len()
|
let mut flag = true;
for (k, v) in &words_sets[i] {
if let Some(n) = char_set.get(k) {
if n < v {
flag = false;
break;
}
} else {
flag = false;
break;
}
}
if flag {
result += words[i].len()
}
}
result as i32
}
fn main() {
dbg!(count_characters(
vec![
"cat".to_string(),
"bt".to_string(),
"hat".to_string(),
"tree".to_string()
],
"atach".to_string()
));
dbg!(count_characters(
vec![
"hello".to_string(),
"world".to_string(),
"leetcode".to_string(),
],
"welldonehoneyr".to_string()
));
}
|
{
continue;
}
|
conditional_block
|
game.rs
|
use common::GeneralError;
use ctrl::{GameController, Gesture};
use gfx::{Scene, SceneBuilder, Window};
use level::Level;
use player::Player;
use sdl2::keyboard::Scancode;
use sdl2::{self, Sdl};
use std::error::Error;
use std::path::PathBuf;
use super::SHADER_ROOT;
use time;
use wad::{Archive, TextureDirectory};
use gfx::TextRenderer;
use math::Vec2f;
pub struct GameConfig {
pub wad_file: PathBuf,
pub metadata_file: PathBuf,
pub level_index: usize,
pub fov: f32,
pub width: u32,
pub height: u32,
}
pub struct Game {
window: Window,
scene: Scene,
text: TextRenderer,
player: Player,
level: Level,
_sdl: Sdl,
control: GameController,
}
impl Game {
pub fn
|
(config: GameConfig) -> Result<Game, Box<Error>> {
let sdl = try!(sdl2::init().map_err(|e| GeneralError(e.0)));
let window = try!(Window::new(&sdl, config.width, config.height));
let wad = try!(Archive::open(&config.wad_file, &config.metadata_file));
let textures = try!(TextureDirectory::from_archive(&wad));
let (level, scene) = {
let mut scene = SceneBuilder::new(&window, PathBuf::from(SHADER_ROOT));
let level = try!(Level::new(&wad, &textures, config.level_index, &mut scene));
let scene = try!(scene.build());
(level, scene)
};
let mut player = Player::new(config.fov, window.aspect_ratio() * 1.2, Default::default());
player.set_position(level.start_pos());
let control = GameController::new(&sdl,
try!(sdl.event_pump().map_err(|e| GeneralError(e.0))));
let text = try!(TextRenderer::new(&window));
Ok(Game {
window: window,
player: player,
level: level,
scene: scene,
text: text,
_sdl: sdl,
control: control,
})
}
pub fn run(&mut self) -> Result<(), Box<Error>> {
let quit_gesture = Gesture::AnyOf(vec![Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape)]);
let grab_toggle_gesture = Gesture::KeyTrigger(Scancode::Grave);
let help_gesture = Gesture::KeyTrigger(Scancode::H);
let short_help = self.text.insert(&self.window, SHORT_HELP, Vec2f::new(0.0, 0.0), 6);
let long_help = self.text.insert(&self.window, LONG_HELP, Vec2f::new(0.0, 0.0), 6);
self.text[long_help].set_visible(false);
let mut current_help = 0;
let mut cum_time = 0.0;
let mut cum_updates_time = 0.0;
let mut num_frames = 0.0;
let mut t0 = time::precise_time_s();
let mut mouse_grabbed = true;
let mut running = true;
while running {
let mut frame = self.window.draw();
let t1 = time::precise_time_s();
let mut delta = (t1 - t0) as f32;
if delta < 1e-10 {
delta = 1.0 / 60.0;
}
let delta = delta;
t0 = t1;
let updates_t0 = time::precise_time_s();
self.control.update();
if self.control.poll_gesture(&quit_gesture) {
running = false;
} else if self.control.poll_gesture(&grab_toggle_gesture) {
mouse_grabbed =!mouse_grabbed;
self.control.set_mouse_enabled(mouse_grabbed);
self.control.set_cursor_grabbed(mouse_grabbed);
} else if self.control.poll_gesture(&help_gesture) {
current_help = current_help % 2 + 1;
match current_help {
0 => self.text[short_help].set_visible(true),
1 => {
self.text[short_help].set_visible(false);
self.text[long_help].set_visible(true);
}
2 => self.text[long_help].set_visible(false),
_ => unreachable!(),
}
}
self.player.update(delta, &self.control, &self.level);
self.scene.set_modelview(&self.player.camera().modelview());
self.scene.set_projection(self.player.camera().projection());
self.level.update(delta, &mut self.scene);
try!(self.scene.render(&mut frame, delta));
try!(self.text.render(&mut frame));
let updates_t1 = time::precise_time_s();
cum_updates_time += updates_t1 - updates_t0;
cum_time += delta as f64;
num_frames += 1.0;
if cum_time > 2.0 {
let fps = num_frames / cum_time;
let cpums = 1000.0 * cum_updates_time / num_frames;
info!("Frame time: {:.2}ms ({:.2}ms cpu, FPS: {:.2})",
1000.0 / fps,
cpums,
fps);
cum_time = 0.0;
cum_updates_time = 0.0;
num_frames = 0.0;
}
// TODO(cristicbz): Re-architect a little bit to support rebuilding the context.
frame.finish().ok().expect("Cannot handle context loss currently :(");
}
Ok(())
}
}
const SHORT_HELP: &'static str = "Press 'h' for help.";
const LONG_HELP: &'static str = r"Use WASD or arrow keys to move and the mouse to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
h - toggle this help message";
|
new
|
identifier_name
|
game.rs
|
use common::GeneralError;
use ctrl::{GameController, Gesture};
use gfx::{Scene, SceneBuilder, Window};
use level::Level;
use player::Player;
use sdl2::keyboard::Scancode;
use sdl2::{self, Sdl};
use std::error::Error;
use std::path::PathBuf;
use super::SHADER_ROOT;
use time;
use wad::{Archive, TextureDirectory};
use gfx::TextRenderer;
use math::Vec2f;
pub struct GameConfig {
pub wad_file: PathBuf,
pub metadata_file: PathBuf,
pub level_index: usize,
pub fov: f32,
pub width: u32,
pub height: u32,
}
pub struct Game {
window: Window,
scene: Scene,
text: TextRenderer,
player: Player,
level: Level,
_sdl: Sdl,
control: GameController,
}
impl Game {
pub fn new(config: GameConfig) -> Result<Game, Box<Error>> {
let sdl = try!(sdl2::init().map_err(|e| GeneralError(e.0)));
let window = try!(Window::new(&sdl, config.width, config.height));
let wad = try!(Archive::open(&config.wad_file, &config.metadata_file));
let textures = try!(TextureDirectory::from_archive(&wad));
let (level, scene) = {
let mut scene = SceneBuilder::new(&window, PathBuf::from(SHADER_ROOT));
let level = try!(Level::new(&wad, &textures, config.level_index, &mut scene));
let scene = try!(scene.build());
(level, scene)
};
let mut player = Player::new(config.fov, window.aspect_ratio() * 1.2, Default::default());
player.set_position(level.start_pos());
let control = GameController::new(&sdl,
try!(sdl.event_pump().map_err(|e| GeneralError(e.0))));
let text = try!(TextRenderer::new(&window));
Ok(Game {
window: window,
player: player,
level: level,
scene: scene,
text: text,
_sdl: sdl,
control: control,
})
}
pub fn run(&mut self) -> Result<(), Box<Error>> {
let quit_gesture = Gesture::AnyOf(vec![Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape)]);
let grab_toggle_gesture = Gesture::KeyTrigger(Scancode::Grave);
let help_gesture = Gesture::KeyTrigger(Scancode::H);
let short_help = self.text.insert(&self.window, SHORT_HELP, Vec2f::new(0.0, 0.0), 6);
let long_help = self.text.insert(&self.window, LONG_HELP, Vec2f::new(0.0, 0.0), 6);
self.text[long_help].set_visible(false);
let mut current_help = 0;
let mut cum_time = 0.0;
let mut cum_updates_time = 0.0;
let mut num_frames = 0.0;
let mut t0 = time::precise_time_s();
let mut mouse_grabbed = true;
let mut running = true;
while running {
let mut frame = self.window.draw();
let t1 = time::precise_time_s();
let mut delta = (t1 - t0) as f32;
if delta < 1e-10 {
delta = 1.0 / 60.0;
}
let delta = delta;
t0 = t1;
let updates_t0 = time::precise_time_s();
self.control.update();
if self.control.poll_gesture(&quit_gesture) {
running = false;
} else if self.control.poll_gesture(&grab_toggle_gesture) {
mouse_grabbed =!mouse_grabbed;
self.control.set_mouse_enabled(mouse_grabbed);
self.control.set_cursor_grabbed(mouse_grabbed);
} else if self.control.poll_gesture(&help_gesture) {
current_help = current_help % 2 + 1;
match current_help {
0 => self.text[short_help].set_visible(true),
1 => {
self.text[short_help].set_visible(false);
self.text[long_help].set_visible(true);
}
|
}
}
self.player.update(delta, &self.control, &self.level);
self.scene.set_modelview(&self.player.camera().modelview());
self.scene.set_projection(self.player.camera().projection());
self.level.update(delta, &mut self.scene);
try!(self.scene.render(&mut frame, delta));
try!(self.text.render(&mut frame));
let updates_t1 = time::precise_time_s();
cum_updates_time += updates_t1 - updates_t0;
cum_time += delta as f64;
num_frames += 1.0;
if cum_time > 2.0 {
let fps = num_frames / cum_time;
let cpums = 1000.0 * cum_updates_time / num_frames;
info!("Frame time: {:.2}ms ({:.2}ms cpu, FPS: {:.2})",
1000.0 / fps,
cpums,
fps);
cum_time = 0.0;
cum_updates_time = 0.0;
num_frames = 0.0;
}
// TODO(cristicbz): Re-architect a little bit to support rebuilding the context.
frame.finish().ok().expect("Cannot handle context loss currently :(");
}
Ok(())
}
}
const SHORT_HELP: &'static str = "Press 'h' for help.";
const LONG_HELP: &'static str = r"Use WASD or arrow keys to move and the mouse to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
h - toggle this help message";
|
2 => self.text[long_help].set_visible(false),
_ => unreachable!(),
|
random_line_split
|
game.rs
|
use common::GeneralError;
use ctrl::{GameController, Gesture};
use gfx::{Scene, SceneBuilder, Window};
use level::Level;
use player::Player;
use sdl2::keyboard::Scancode;
use sdl2::{self, Sdl};
use std::error::Error;
use std::path::PathBuf;
use super::SHADER_ROOT;
use time;
use wad::{Archive, TextureDirectory};
use gfx::TextRenderer;
use math::Vec2f;
pub struct GameConfig {
pub wad_file: PathBuf,
pub metadata_file: PathBuf,
pub level_index: usize,
pub fov: f32,
pub width: u32,
pub height: u32,
}
pub struct Game {
window: Window,
scene: Scene,
text: TextRenderer,
player: Player,
level: Level,
_sdl: Sdl,
control: GameController,
}
impl Game {
pub fn new(config: GameConfig) -> Result<Game, Box<Error>> {
let sdl = try!(sdl2::init().map_err(|e| GeneralError(e.0)));
let window = try!(Window::new(&sdl, config.width, config.height));
let wad = try!(Archive::open(&config.wad_file, &config.metadata_file));
let textures = try!(TextureDirectory::from_archive(&wad));
let (level, scene) = {
let mut scene = SceneBuilder::new(&window, PathBuf::from(SHADER_ROOT));
let level = try!(Level::new(&wad, &textures, config.level_index, &mut scene));
let scene = try!(scene.build());
(level, scene)
};
let mut player = Player::new(config.fov, window.aspect_ratio() * 1.2, Default::default());
player.set_position(level.start_pos());
let control = GameController::new(&sdl,
try!(sdl.event_pump().map_err(|e| GeneralError(e.0))));
let text = try!(TextRenderer::new(&window));
Ok(Game {
window: window,
player: player,
level: level,
scene: scene,
text: text,
_sdl: sdl,
control: control,
})
}
pub fn run(&mut self) -> Result<(), Box<Error>> {
let quit_gesture = Gesture::AnyOf(vec![Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape)]);
let grab_toggle_gesture = Gesture::KeyTrigger(Scancode::Grave);
let help_gesture = Gesture::KeyTrigger(Scancode::H);
let short_help = self.text.insert(&self.window, SHORT_HELP, Vec2f::new(0.0, 0.0), 6);
let long_help = self.text.insert(&self.window, LONG_HELP, Vec2f::new(0.0, 0.0), 6);
self.text[long_help].set_visible(false);
let mut current_help = 0;
let mut cum_time = 0.0;
let mut cum_updates_time = 0.0;
let mut num_frames = 0.0;
let mut t0 = time::precise_time_s();
let mut mouse_grabbed = true;
let mut running = true;
while running {
let mut frame = self.window.draw();
let t1 = time::precise_time_s();
let mut delta = (t1 - t0) as f32;
if delta < 1e-10 {
delta = 1.0 / 60.0;
}
let delta = delta;
t0 = t1;
let updates_t0 = time::precise_time_s();
self.control.update();
if self.control.poll_gesture(&quit_gesture)
|
else if self.control.poll_gesture(&grab_toggle_gesture) {
mouse_grabbed =!mouse_grabbed;
self.control.set_mouse_enabled(mouse_grabbed);
self.control.set_cursor_grabbed(mouse_grabbed);
} else if self.control.poll_gesture(&help_gesture) {
current_help = current_help % 2 + 1;
match current_help {
0 => self.text[short_help].set_visible(true),
1 => {
self.text[short_help].set_visible(false);
self.text[long_help].set_visible(true);
}
2 => self.text[long_help].set_visible(false),
_ => unreachable!(),
}
}
self.player.update(delta, &self.control, &self.level);
self.scene.set_modelview(&self.player.camera().modelview());
self.scene.set_projection(self.player.camera().projection());
self.level.update(delta, &mut self.scene);
try!(self.scene.render(&mut frame, delta));
try!(self.text.render(&mut frame));
let updates_t1 = time::precise_time_s();
cum_updates_time += updates_t1 - updates_t0;
cum_time += delta as f64;
num_frames += 1.0;
if cum_time > 2.0 {
let fps = num_frames / cum_time;
let cpums = 1000.0 * cum_updates_time / num_frames;
info!("Frame time: {:.2}ms ({:.2}ms cpu, FPS: {:.2})",
1000.0 / fps,
cpums,
fps);
cum_time = 0.0;
cum_updates_time = 0.0;
num_frames = 0.0;
}
// TODO(cristicbz): Re-architect a little bit to support rebuilding the context.
frame.finish().ok().expect("Cannot handle context loss currently :(");
}
Ok(())
}
}
const SHORT_HELP: &'static str = "Press 'h' for help.";
const LONG_HELP: &'static str = r"Use WASD or arrow keys to move and the mouse to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
h - toggle this help message";
|
{
running = false;
}
|
conditional_block
|
nil-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
// 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.
// LLDB can't handle zero-sized values
// ignore-lldb
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:run
// gdb-command:print first
// gdb-check:$1 = {<No data fields>}
// gdb-command:print second
// gdb-check:$2 = {<No data fields>}
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
enum ANilEnum {}
enum AnotherNilEnum {}
// This test relies on gdb printing the string "{<No data fields>}" for empty
// structs (which may change some time)
fn main() {
unsafe {
let first: ANilEnum = ::std::mem::zeroed();
let second: AnotherNilEnum = ::std::mem::zeroed();
zzz(); // #break
}
}
fn zzz() {()}
|
// 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
|
random_line_split
|
nil-enum.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// LLDB can't handle zero-sized values
// ignore-lldb
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:run
// gdb-command:print first
// gdb-check:$1 = {<No data fields>}
// gdb-command:print second
// gdb-check:$2 = {<No data fields>}
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
enum
|
{}
enum AnotherNilEnum {}
// This test relies on gdb printing the string "{<No data fields>}" for empty
// structs (which may change some time)
fn main() {
unsafe {
let first: ANilEnum = ::std::mem::zeroed();
let second: AnotherNilEnum = ::std::mem::zeroed();
zzz(); // #break
}
}
fn zzz() {()}
|
ANilEnum
|
identifier_name
|
client.rs
|
// A client to the server.
// Contains its own map and response variables
use super::super::ui::*;
use super::*;
use context::*;
pub struct Client {
connection: ClientConn,
pub map: Map,
pub side: Side,
response_queue: Vec<Response>,
}
impl Client {
pub fn new(mut connection: ClientConn) -> Result<Self> {
let initial_state = connection.recv_blocking()?;
let (map, side) = match initial_state {
ServerMessage::InitialState { map, side } => (map, side),
ServerMessage::GameFull => return Err("Game full".into()),
message => {
return Err(format!(
"Wrong type of message recieved, expected initial state, got: {:?}",
message
)
.into())
}
};
Ok(Self {
connection,
map,
side,
response_queue: Vec::new(),
})
}
pub fn responses(&self) -> &[Response] {
&self.response_queue
}
pub fn new_from_addr(addr: &str) -> Result<Self>
|
pub fn recv(&mut self) -> bool {
let mut recieved_message = false;
while let Ok(message) = self.connection.recv() {
match message {
ServerMessage::Responses(mut responses) => {
self.response_queue.append(&mut responses)
}
_ => unreachable!(),
}
recieved_message = true;
}
recieved_message
}
pub fn process_responses(
&mut self,
dt: f32,
ctx: &mut Context,
ui: &mut Interface,
camera: &mut Camera,
) {
let mut i = 0;
while i < self.response_queue.len() {
let status = self.response_queue[i].step(dt, self.side, &mut self.map, ctx, ui, camera);
if status.finished {
self.response_queue.remove(0);
} else {
i += 1;
}
if status.blocking {
break;
}
}
}
pub fn process_state_updates(&mut self) -> (bool, bool) {
let mut invalid_command = false;
for response in self.response_queue.drain(..) {
match response {
Response::NewState(map) => self.map = map,
Response::GameOver(_) => return (true, invalid_command),
Response::InvalidCommand => invalid_command = true,
_ => {}
}
}
(false, invalid_command)
}
pub fn visibility_at(&self, x: usize, y: usize) -> Visibility {
self.map.tiles.visibility_at(x, y, self.side)
}
pub fn our_turn(&self) -> bool {
self.side == self.map.side
}
fn send_command(&self, unit: u8, command: Command) {
self.connection
.send(ClientMessage::Command { unit, command })
.unwrap();
}
pub fn walk(&self, unit: u8, path: &[PathPoint]) {
self.send_command(unit, Command::walk(path));
}
pub fn turn(&self, unit: u8, facing: UnitFacing) {
self.send_command(unit, Command::Turn(facing));
}
pub fn fire(&self, unit: u8, x: usize, y: usize) {
self.send_command(unit, Command::Fire { x, y });
}
pub fn use_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::UseItem(item));
}
pub fn drop_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::DropItem(item));
}
pub fn pickup_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::PickupItem(item));
}
pub fn throw_item(&self, unit: u8, item: usize, x: usize, y: usize) {
self.send_command(unit, Command::ThrowItem { item, x, y });
}
pub fn end_turn(&self) {
self.connection.send(ClientMessage::EndTurn).unwrap();
}
pub fn save(&self, filename: &str) {
self.connection
.send(ClientMessage::SaveGame(filename.into()))
.unwrap();
}
}
|
{
let client_stream = TcpStream::connect(addr)
.chain_err(|| format!("Failed to connect to server at '{}'", addr))?;
let connection = Connection::new_tcp(client_stream)?;
Client::new(connection)
}
|
identifier_body
|
client.rs
|
// A client to the server.
// Contains its own map and response variables
use super::super::ui::*;
use super::*;
use context::*;
pub struct Client {
connection: ClientConn,
pub map: Map,
pub side: Side,
response_queue: Vec<Response>,
}
impl Client {
pub fn new(mut connection: ClientConn) -> Result<Self> {
let initial_state = connection.recv_blocking()?;
let (map, side) = match initial_state {
ServerMessage::InitialState { map, side } => (map, side),
ServerMessage::GameFull => return Err("Game full".into()),
message => {
return Err(format!(
"Wrong type of message recieved, expected initial state, got: {:?}",
message
)
.into())
}
};
Ok(Self {
connection,
map,
side,
response_queue: Vec::new(),
})
}
pub fn responses(&self) -> &[Response] {
&self.response_queue
}
pub fn new_from_addr(addr: &str) -> Result<Self> {
let client_stream = TcpStream::connect(addr)
.chain_err(|| format!("Failed to connect to server at '{}'", addr))?;
let connection = Connection::new_tcp(client_stream)?;
Client::new(connection)
}
pub fn recv(&mut self) -> bool {
let mut recieved_message = false;
while let Ok(message) = self.connection.recv() {
match message {
ServerMessage::Responses(mut responses) => {
self.response_queue.append(&mut responses)
}
_ => unreachable!(),
}
recieved_message = true;
}
recieved_message
}
pub fn process_responses(
&mut self,
dt: f32,
ctx: &mut Context,
ui: &mut Interface,
camera: &mut Camera,
) {
let mut i = 0;
while i < self.response_queue.len() {
let status = self.response_queue[i].step(dt, self.side, &mut self.map, ctx, ui, camera);
if status.finished {
self.response_queue.remove(0);
} else {
i += 1;
}
if status.blocking {
break;
}
}
}
pub fn process_state_updates(&mut self) -> (bool, bool) {
let mut invalid_command = false;
for response in self.response_queue.drain(..) {
match response {
Response::NewState(map) => self.map = map,
Response::GameOver(_) => return (true, invalid_command),
Response::InvalidCommand => invalid_command = true,
_ => {}
}
}
(false, invalid_command)
}
pub fn visibility_at(&self, x: usize, y: usize) -> Visibility {
self.map.tiles.visibility_at(x, y, self.side)
}
pub fn our_turn(&self) -> bool {
self.side == self.map.side
}
fn send_command(&self, unit: u8, command: Command) {
self.connection
.send(ClientMessage::Command { unit, command })
.unwrap();
}
pub fn
|
(&self, unit: u8, path: &[PathPoint]) {
self.send_command(unit, Command::walk(path));
}
pub fn turn(&self, unit: u8, facing: UnitFacing) {
self.send_command(unit, Command::Turn(facing));
}
pub fn fire(&self, unit: u8, x: usize, y: usize) {
self.send_command(unit, Command::Fire { x, y });
}
pub fn use_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::UseItem(item));
}
pub fn drop_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::DropItem(item));
}
pub fn pickup_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::PickupItem(item));
}
pub fn throw_item(&self, unit: u8, item: usize, x: usize, y: usize) {
self.send_command(unit, Command::ThrowItem { item, x, y });
}
pub fn end_turn(&self) {
self.connection.send(ClientMessage::EndTurn).unwrap();
}
pub fn save(&self, filename: &str) {
self.connection
.send(ClientMessage::SaveGame(filename.into()))
.unwrap();
}
}
|
walk
|
identifier_name
|
client.rs
|
// A client to the server.
// Contains its own map and response variables
use super::super::ui::*;
use super::*;
use context::*;
pub struct Client {
connection: ClientConn,
pub map: Map,
pub side: Side,
response_queue: Vec<Response>,
}
impl Client {
pub fn new(mut connection: ClientConn) -> Result<Self> {
let initial_state = connection.recv_blocking()?;
let (map, side) = match initial_state {
ServerMessage::InitialState { map, side } => (map, side),
ServerMessage::GameFull => return Err("Game full".into()),
message => {
return Err(format!(
"Wrong type of message recieved, expected initial state, got: {:?}",
message
)
.into())
}
};
Ok(Self {
connection,
map,
side,
response_queue: Vec::new(),
})
}
pub fn responses(&self) -> &[Response] {
&self.response_queue
}
pub fn new_from_addr(addr: &str) -> Result<Self> {
let client_stream = TcpStream::connect(addr)
.chain_err(|| format!("Failed to connect to server at '{}'", addr))?;
let connection = Connection::new_tcp(client_stream)?;
Client::new(connection)
}
pub fn recv(&mut self) -> bool {
let mut recieved_message = false;
while let Ok(message) = self.connection.recv() {
match message {
ServerMessage::Responses(mut responses) => {
self.response_queue.append(&mut responses)
}
_ => unreachable!(),
}
recieved_message = true;
}
recieved_message
}
pub fn process_responses(
&mut self,
dt: f32,
ctx: &mut Context,
ui: &mut Interface,
camera: &mut Camera,
) {
let mut i = 0;
while i < self.response_queue.len() {
let status = self.response_queue[i].step(dt, self.side, &mut self.map, ctx, ui, camera);
|
i += 1;
}
if status.blocking {
break;
}
}
}
pub fn process_state_updates(&mut self) -> (bool, bool) {
let mut invalid_command = false;
for response in self.response_queue.drain(..) {
match response {
Response::NewState(map) => self.map = map,
Response::GameOver(_) => return (true, invalid_command),
Response::InvalidCommand => invalid_command = true,
_ => {}
}
}
(false, invalid_command)
}
pub fn visibility_at(&self, x: usize, y: usize) -> Visibility {
self.map.tiles.visibility_at(x, y, self.side)
}
pub fn our_turn(&self) -> bool {
self.side == self.map.side
}
fn send_command(&self, unit: u8, command: Command) {
self.connection
.send(ClientMessage::Command { unit, command })
.unwrap();
}
pub fn walk(&self, unit: u8, path: &[PathPoint]) {
self.send_command(unit, Command::walk(path));
}
pub fn turn(&self, unit: u8, facing: UnitFacing) {
self.send_command(unit, Command::Turn(facing));
}
pub fn fire(&self, unit: u8, x: usize, y: usize) {
self.send_command(unit, Command::Fire { x, y });
}
pub fn use_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::UseItem(item));
}
pub fn drop_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::DropItem(item));
}
pub fn pickup_item(&self, unit: u8, item: usize) {
self.send_command(unit, Command::PickupItem(item));
}
pub fn throw_item(&self, unit: u8, item: usize, x: usize, y: usize) {
self.send_command(unit, Command::ThrowItem { item, x, y });
}
pub fn end_turn(&self) {
self.connection.send(ClientMessage::EndTurn).unwrap();
}
pub fn save(&self, filename: &str) {
self.connection
.send(ClientMessage::SaveGame(filename.into()))
.unwrap();
}
}
|
if status.finished {
self.response_queue.remove(0);
} else {
|
random_line_split
|
lang_items.rs
|
/// Default panic handler
#[linkage = "weak"]
#[lang = "panic_fmt"]
unsafe extern "C" fn panic_fmt(
_args: ::core::fmt::Arguments,
_file: &'static str,
_line: u32,
) ->! {
hprint!("panicked at '");
match () {
#[cfg(feature = "semihosting")]
() => {
::cortex_m_semihosting::io::write_fmt(_args);
}
#[cfg(not(feature = "semihosting"))]
() => {}
}
hprintln!("', {}:{}", _file, _line);
bkpt!();
loop {}
}
/// Lang item required to make the normal `main` work in applications
// This is how the `start` lang item works:
// When `rustc` compiles a binary crate, it creates a `main` function that looks
// like this:
//
// ```
// #[export_name = "main"]
// pub extern "C" fn rustc_main(argc: isize, argv: *const *const u8) -> isize {
// start(main)
// }
// ```
//
// Where `start` is this function and `main` is the binary crate's `main`
// function.
//
// The final piece is that the entry point of our program, the reset handler,
// has to call `rustc_main`. That's covered by the `reset_handler` function in
// `src/exceptions.rs`
#[lang = "start"]
extern "C" fn start(main: fn(), _argc: isize, _argv: *const *const u8) -> isize
|
{
main();
0
}
|
identifier_body
|
|
lang_items.rs
|
/// Default panic handler
#[linkage = "weak"]
#[lang = "panic_fmt"]
unsafe extern "C" fn panic_fmt(
_args: ::core::fmt::Arguments,
_file: &'static str,
_line: u32,
) ->! {
hprint!("panicked at '");
match () {
#[cfg(feature = "semihosting")]
() => {
::cortex_m_semihosting::io::write_fmt(_args);
}
#[cfg(not(feature = "semihosting"))]
() =>
|
}
hprintln!("', {}:{}", _file, _line);
bkpt!();
loop {}
}
/// Lang item required to make the normal `main` work in applications
// This is how the `start` lang item works:
// When `rustc` compiles a binary crate, it creates a `main` function that looks
// like this:
//
// ```
// #[export_name = "main"]
// pub extern "C" fn rustc_main(argc: isize, argv: *const *const u8) -> isize {
// start(main)
// }
// ```
//
// Where `start` is this function and `main` is the binary crate's `main`
// function.
//
// The final piece is that the entry point of our program, the reset handler,
// has to call `rustc_main`. That's covered by the `reset_handler` function in
// `src/exceptions.rs`
#[lang = "start"]
extern "C" fn start(main: fn(), _argc: isize, _argv: *const *const u8) -> isize {
main();
0
}
|
{}
|
conditional_block
|
lang_items.rs
|
/// Default panic handler
#[linkage = "weak"]
#[lang = "panic_fmt"]
unsafe extern "C" fn panic_fmt(
_args: ::core::fmt::Arguments,
_file: &'static str,
_line: u32,
) ->! {
hprint!("panicked at '");
match () {
#[cfg(feature = "semihosting")]
() => {
::cortex_m_semihosting::io::write_fmt(_args);
}
#[cfg(not(feature = "semihosting"))]
() => {}
}
hprintln!("', {}:{}", _file, _line);
bkpt!();
loop {}
}
/// Lang item required to make the normal `main` work in applications
// This is how the `start` lang item works:
// When `rustc` compiles a binary crate, it creates a `main` function that looks
// like this:
//
// ```
// #[export_name = "main"]
// pub extern "C" fn rustc_main(argc: isize, argv: *const *const u8) -> isize {
// start(main)
// }
// ```
//
// Where `start` is this function and `main` is the binary crate's `main`
// function.
//
// The final piece is that the entry point of our program, the reset handler,
// has to call `rustc_main`. That's covered by the `reset_handler` function in
// `src/exceptions.rs`
#[lang = "start"]
extern "C" fn
|
(main: fn(), _argc: isize, _argv: *const *const u8) -> isize {
main();
0
}
|
start
|
identifier_name
|
lang_items.rs
|
/// Default panic handler
#[linkage = "weak"]
#[lang = "panic_fmt"]
unsafe extern "C" fn panic_fmt(
_args: ::core::fmt::Arguments,
_file: &'static str,
_line: u32,
) ->! {
hprint!("panicked at '");
match () {
#[cfg(feature = "semihosting")]
() => {
::cortex_m_semihosting::io::write_fmt(_args);
}
#[cfg(not(feature = "semihosting"))]
() => {}
}
hprintln!("', {}:{}", _file, _line);
bkpt!();
loop {}
}
/// Lang item required to make the normal `main` work in applications
// This is how the `start` lang item works:
// When `rustc` compiles a binary crate, it creates a `main` function that looks
// like this:
//
// ```
// #[export_name = "main"]
// pub extern "C" fn rustc_main(argc: isize, argv: *const *const u8) -> isize {
// start(main)
// }
// ```
//
// Where `start` is this function and `main` is the binary crate's `main`
// function.
|
//
// The final piece is that the entry point of our program, the reset handler,
// has to call `rustc_main`. That's covered by the `reset_handler` function in
// `src/exceptions.rs`
#[lang = "start"]
extern "C" fn start(main: fn(), _argc: isize, _argv: *const *const u8) -> isize {
main();
0
}
|
random_line_split
|
|
block-iter-2.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
fn iter_vec<T>(v: ~[T], f: |&T|)
|
pub fn main() {
let v = ~[1, 2, 3, 4, 5];
let mut sum = 0;
iter_vec(v.clone(), |i| {
iter_vec(v.clone(), |j| {
sum += *i * *j;
});
});
error!("{:?}", sum);
assert_eq!(sum, 225);
}
|
{ for x in v.iter() { f(x); } }
|
identifier_body
|
block-iter-2.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
fn
|
<T>(v: ~[T], f: |&T|) { for x in v.iter() { f(x); } }
pub fn main() {
let v = ~[1, 2, 3, 4, 5];
let mut sum = 0;
iter_vec(v.clone(), |i| {
iter_vec(v.clone(), |j| {
sum += *i * *j;
});
});
error!("{:?}", sum);
assert_eq!(sum, 225);
}
|
iter_vec
|
identifier_name
|
block-iter-2.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
fn iter_vec<T>(v: ~[T], f: |&T|) { for x in v.iter() { f(x); } }
pub fn main() {
let v = ~[1, 2, 3, 4, 5];
let mut sum = 0;
iter_vec(v.clone(), |i| {
iter_vec(v.clone(), |j| {
sum += *i * *j;
});
});
error!("{:?}", sum);
assert_eq!(sum, 225);
}
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
|
random_line_split
|
clipboard_provider.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 ipc_channel::ipc;
use msg::constellation_msg::ConstellationChan;
use msg::constellation_msg::Msg as ConstellationMsg;
use std::borrow::ToOwned;
use std::sync::mpsc::channel;
pub trait ClipboardProvider {
// blocking method to get the clipboard contents
fn clipboard_contents(&mut self) -> String;
// blocking method to set the clipboard contents
fn set_clipboard_contents(&mut self, String);
}
impl ClipboardProvider for ConstellationChan {
fn clipboard_contents(&mut self) -> String {
let (tx, rx) = ipc::channel().unwrap();
self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap();
rx.recv().unwrap()
}
fn set_clipboard_contents(&mut self, s: String) {
self.0.send(ConstellationMsg::SetClipboardContents(s)).unwrap();
}
}
pub struct DummyClipboardContext {
content: String
}
impl DummyClipboardContext {
pub fn new(s: &str) -> DummyClipboardContext {
DummyClipboardContext {
content: s.to_owned()
}
}
}
impl ClipboardProvider for DummyClipboardContext {
fn
|
(&mut self) -> String {
self.content.clone()
}
fn set_clipboard_contents(&mut self, s: String) {
self.content = s;
}
}
|
clipboard_contents
|
identifier_name
|
clipboard_provider.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 ipc_channel::ipc;
use msg::constellation_msg::ConstellationChan;
use msg::constellation_msg::Msg as ConstellationMsg;
use std::borrow::ToOwned;
use std::sync::mpsc::channel;
pub trait ClipboardProvider {
// blocking method to get the clipboard contents
fn clipboard_contents(&mut self) -> String;
// blocking method to set the clipboard contents
fn set_clipboard_contents(&mut self, String);
}
impl ClipboardProvider for ConstellationChan {
fn clipboard_contents(&mut self) -> String {
let (tx, rx) = ipc::channel().unwrap();
self.0.send(ConstellationMsg::GetClipboardContents(tx)).unwrap();
rx.recv().unwrap()
}
fn set_clipboard_contents(&mut self, s: String) {
self.0.send(ConstellationMsg::SetClipboardContents(s)).unwrap();
|
}
}
pub struct DummyClipboardContext {
content: String
}
impl DummyClipboardContext {
pub fn new(s: &str) -> DummyClipboardContext {
DummyClipboardContext {
content: s.to_owned()
}
}
}
impl ClipboardProvider for DummyClipboardContext {
fn clipboard_contents(&mut self) -> String {
self.content.clone()
}
fn set_clipboard_contents(&mut self, s: String) {
self.content = s;
}
}
|
random_line_split
|
|
lib.rs
|
//! stal-rs
//! ====
//!
//! Set algebra solver for Redis in Rust, based on
//! [Stal](https://github.com/soveran/stal).
//!
//! Description
//! -----------
//!
|
//!
//! Usage
//! -----
//!
//! `stal-rs` has no dependencies. It produces a vector of Redis operations that
//! have to be run by the user.
//!
//! ```rust
//! extern crate stal;
//!
//! let foobar = stal::Set::Inter(vec![stal::Set::Key(b"foo".to_vec()), stal::Set::Key(b"bar".to_vec())]);
//! let foobar_nobaz = stal::Set::Diff(vec![foobar, stal::Set::Key(b"baz".to_vec())]);
//! let foobar_nobaz_andqux = stal::Set::Union(vec![stal::Set::Key(b"qux".to_vec()), foobar_nobaz]);
//!
//! assert_eq!(
//! stal::Stal::new("SMEMBERS".to_string(), foobar_nobaz_andqux).solve(),
//! (
//! vec![
//! vec![b"MULTI".to_vec()],
//! vec![b"SINTERSTORE".to_vec(), b"stal:2".to_vec(), b"foo".to_vec(), b"bar".to_vec()],
//! vec![b"SDIFFSTORE".to_vec(), b"stal:1".to_vec(), b"stal:2".to_vec(), b"baz".to_vec()],
//! vec![b"SUNIONSTORE".to_vec(), b"stal:0".to_vec(), b"qux".to_vec(), b"stal:1".to_vec()],
//! vec![b"SMEMBERS".to_vec(), b"stal:0".to_vec()],
//! vec![b"DEL".to_vec(), b"stal:0".to_vec(), b"stal:1".to_vec(), b"stal:2".to_vec()],
//! vec![b"EXEC".to_vec()],
//! ],
//! 4
//! ));
//! ```
//!
//! `stal-rs` translates the internal calls to `SUNION`, `SDIFF` and
//! `SINTER` into `SDIFFSTORE`, `SINTERSTORE` and `SUNIONSTORE` to
//! perform the underlying operations, and it takes care of generating
//! and deleting any temporary keys.
//!
//! The outmost command can be any set operation, for example:
//!
//! ```rust
//! extern crate stal;
//! let myset = stal::Set::Key(b"my set".to_vec());
//! stal::Stal::new("SCARD".to_string(), myset).solve();
//! ```
//!
//! If you want to preview the commands `Stal` will send to generate
//! the results, you can use `Stal.explain`:
//!
//! ```rust
//! extern crate stal;
//!
//! assert_eq!(
//! stal::Stal::new("SMEMBERS".to_string(),
//! stal::Set::Inter(vec![
//! stal::Set::Union(vec![
//! stal::Set::Key(b"foo".to_vec()),
//! stal::Set::Key(b"bar".to_vec()),
//! ]),
//! stal::Set::Key(b"baz".to_vec()),
//! ])
//! ).explain(),
//! vec![
//! vec![b"SUNIONSTORE".to_vec(), b"stal:1".to_vec(), b"foo".to_vec(), b"bar".to_vec()],
//! vec![b"SINTERSTORE".to_vec(), b"stal:0".to_vec(), b"stal:1".to_vec(), b"baz".to_vec()],
//! vec![b"SMEMBERS".to_vec(), b"stal:0".to_vec()],
//! ]
//! )
//! ```
//!
//! All commands are wrapped in a `MULTI/EXEC` transaction.
//!
//! [redis]: http://redis.io
#![crate_name = "stal"]
#![crate_type = "lib"]
/// A set of values. It can be generated from a Redis key or from a set
/// operation based on other sets.
#[derive(Debug, Clone)]
pub enum Set {
/// A key
Key(Vec<u8>),
/// All the elements in any of the provided sets
Union(Vec<Set>),
/// All the elements in all the sets
Inter(Vec<Set>),
/// All the elements in the first set that are not in the other sets
Diff(Vec<Set>),
}
use Set::*;
impl Set {
/// Gets the commands to get a list of ids for this set
pub fn into_ids(self) -> Stal {
let (op, sets) = match self {
Key(_) => return Stal::from_template(vec![b"SMEMBERS".to_vec(), vec![]], vec![(self, 1)]),
Union(sets) => ("SUNION", sets),
Inter(sets) => ("SINTER", sets),
Diff(sets) => ("SDIFF", sets),
};
let mut command = vec![op.as_bytes().to_vec()];
command.extend(sets.iter().map(|_| vec![]).collect::<Vec<_>>());
let mut setv = vec![];
let mut i = 1;
for set in sets.into_iter() {
setv.push((set, i));
i += 1;
}
Stal::from_template(command, setv)
}
/// Gets the commands to get a list of ids for this set
pub fn ids(&self) -> Stal {
let (op, sets) = match *self {
Key(_) => return Stal::from_template(vec![b"SMEMBERS".to_vec(), vec![]], vec![(self.clone(), 1)]),
Union(ref sets) => ("SUNION", sets),
Inter(ref sets) => ("SINTER", sets),
Diff(ref sets) => ("SDIFF", sets),
};
let mut command = vec![op.as_bytes().to_vec()];
command.extend(sets.iter().map(|_| vec![]).collect::<Vec<_>>());
let mut setv = vec![];
for i in 0..sets.len() {
setv.push((sets[i].clone(), i + 1));
}
Stal::from_template(command, setv)
}
/// Maps the operation to its Redis command name.
fn command(&self) -> &'static str {
match *self {
Key(_) => unreachable!(),
Union(_) => "SUNIONSTORE",
Inter(_) => "SINTERSTORE",
Diff(_) => "SDIFFSTORE",
}
}
/// Appends the operation to `ops` and any temporary id created to `ids`.
/// Returns the key representing the set.
pub fn convert(&self, ids: &mut Vec<String>, ops: &mut Vec<Vec<Vec<u8>>>) -> Vec<u8> {
let sets = match *self {
Key(ref k) => return k.clone(),
Union(ref sets) => sets,
Inter(ref sets) => sets,
Diff(ref sets) => sets,
};
let mut op = Vec::with_capacity(2 + sets.len());
let id = format!("stal:{}", ids.len());
let r = id.as_bytes().to_vec();
ids.push(id);
op.push(self.command().as_bytes().to_vec());
op.push(r.clone());
op.extend(sets.into_iter().map(|s| s.convert(ids, ops)));
ops.push(op);
r
}
}
/// An operation to be executed on a set
#[derive(Debug)]
pub struct Stal {
/// A Redis command
command: Vec<Vec<u8>>,
/// Set in which execute the operation
sets: Vec<(Set, usize)>,
}
impl Stal {
pub fn new(operation: String, set: Set) -> Self {
Stal {
command: vec![operation.as_bytes().to_vec(), vec![]],
sets: vec![(set, 1)],
}
}
/// Takes an arbitrary command that uses one or more sets. The `command`
/// must have placeholders where the set keys should go. Each element
/// in `sets` specifies the position in the `command`.
pub fn from_template(command: Vec<Vec<u8>>, sets: Vec<(Set, usize)>) -> Self {
Stal {
command: command,
sets: sets,
}
}
fn add_ops(&self, ids: &mut Vec<String>, ops: &mut Vec<Vec<Vec<u8>>>) {
let mut command = self.command.clone();
for args in self.sets.iter() {
command.push(args.0.convert(ids, ops));
command.swap_remove(args.1);
}
ops.push(command);
}
/// Returns a list of operations to run. For debug only.
pub fn explain(&self) -> Vec<Vec<Vec<u8>>> {
let mut ids = vec![];
let mut ops = vec![];
self.add_ops(&mut ids, &mut ops);
ops
}
/// Returns a lit of operations, wrapped in a multi/exec.
/// The last operation is always exec, and the returned `usize` indicates
/// the return value of the `operation`.
pub fn solve(&self) -> (Vec<Vec<Vec<u8>>>, usize) {
let mut ids = vec![];
let mut ops = vec![vec![b"MULTI".to_vec()]];
self.add_ops(&mut ids, &mut ops);
let pos = ops.len() - 1;
if ids.len() > 0 {
let mut del = vec![b"DEL".to_vec()];
del.extend(ids.into_iter().map(|x| x.as_bytes().to_vec()));
ops.push(del);
}
ops.push(vec![b"EXEC".to_vec()]);
(ops, pos)
}
}
|
//! `stal-rs` provide set operations and resolves them in [Redis][redis].
|
random_line_split
|
lib.rs
|
//! stal-rs
//! ====
//!
//! Set algebra solver for Redis in Rust, based on
//! [Stal](https://github.com/soveran/stal).
//!
//! Description
//! -----------
//!
//! `stal-rs` provide set operations and resolves them in [Redis][redis].
//!
//! Usage
//! -----
//!
//! `stal-rs` has no dependencies. It produces a vector of Redis operations that
//! have to be run by the user.
//!
//! ```rust
//! extern crate stal;
//!
//! let foobar = stal::Set::Inter(vec![stal::Set::Key(b"foo".to_vec()), stal::Set::Key(b"bar".to_vec())]);
//! let foobar_nobaz = stal::Set::Diff(vec![foobar, stal::Set::Key(b"baz".to_vec())]);
//! let foobar_nobaz_andqux = stal::Set::Union(vec![stal::Set::Key(b"qux".to_vec()), foobar_nobaz]);
//!
//! assert_eq!(
//! stal::Stal::new("SMEMBERS".to_string(), foobar_nobaz_andqux).solve(),
//! (
//! vec![
//! vec![b"MULTI".to_vec()],
//! vec![b"SINTERSTORE".to_vec(), b"stal:2".to_vec(), b"foo".to_vec(), b"bar".to_vec()],
//! vec![b"SDIFFSTORE".to_vec(), b"stal:1".to_vec(), b"stal:2".to_vec(), b"baz".to_vec()],
//! vec![b"SUNIONSTORE".to_vec(), b"stal:0".to_vec(), b"qux".to_vec(), b"stal:1".to_vec()],
//! vec![b"SMEMBERS".to_vec(), b"stal:0".to_vec()],
//! vec![b"DEL".to_vec(), b"stal:0".to_vec(), b"stal:1".to_vec(), b"stal:2".to_vec()],
//! vec![b"EXEC".to_vec()],
//! ],
//! 4
//! ));
//! ```
//!
//! `stal-rs` translates the internal calls to `SUNION`, `SDIFF` and
//! `SINTER` into `SDIFFSTORE`, `SINTERSTORE` and `SUNIONSTORE` to
//! perform the underlying operations, and it takes care of generating
//! and deleting any temporary keys.
//!
//! The outmost command can be any set operation, for example:
//!
//! ```rust
//! extern crate stal;
//! let myset = stal::Set::Key(b"my set".to_vec());
//! stal::Stal::new("SCARD".to_string(), myset).solve();
//! ```
//!
//! If you want to preview the commands `Stal` will send to generate
//! the results, you can use `Stal.explain`:
//!
//! ```rust
//! extern crate stal;
//!
//! assert_eq!(
//! stal::Stal::new("SMEMBERS".to_string(),
//! stal::Set::Inter(vec![
//! stal::Set::Union(vec![
//! stal::Set::Key(b"foo".to_vec()),
//! stal::Set::Key(b"bar".to_vec()),
//! ]),
//! stal::Set::Key(b"baz".to_vec()),
//! ])
//! ).explain(),
//! vec![
//! vec![b"SUNIONSTORE".to_vec(), b"stal:1".to_vec(), b"foo".to_vec(), b"bar".to_vec()],
//! vec![b"SINTERSTORE".to_vec(), b"stal:0".to_vec(), b"stal:1".to_vec(), b"baz".to_vec()],
//! vec![b"SMEMBERS".to_vec(), b"stal:0".to_vec()],
//! ]
//! )
//! ```
//!
//! All commands are wrapped in a `MULTI/EXEC` transaction.
//!
//! [redis]: http://redis.io
#![crate_name = "stal"]
#![crate_type = "lib"]
/// A set of values. It can be generated from a Redis key or from a set
/// operation based on other sets.
#[derive(Debug, Clone)]
pub enum Set {
/// A key
Key(Vec<u8>),
/// All the elements in any of the provided sets
Union(Vec<Set>),
/// All the elements in all the sets
Inter(Vec<Set>),
/// All the elements in the first set that are not in the other sets
Diff(Vec<Set>),
}
use Set::*;
impl Set {
/// Gets the commands to get a list of ids for this set
pub fn into_ids(self) -> Stal {
let (op, sets) = match self {
Key(_) => return Stal::from_template(vec![b"SMEMBERS".to_vec(), vec![]], vec![(self, 1)]),
Union(sets) => ("SUNION", sets),
Inter(sets) => ("SINTER", sets),
Diff(sets) => ("SDIFF", sets),
};
let mut command = vec![op.as_bytes().to_vec()];
command.extend(sets.iter().map(|_| vec![]).collect::<Vec<_>>());
let mut setv = vec![];
let mut i = 1;
for set in sets.into_iter() {
setv.push((set, i));
i += 1;
}
Stal::from_template(command, setv)
}
/// Gets the commands to get a list of ids for this set
pub fn ids(&self) -> Stal {
let (op, sets) = match *self {
Key(_) => return Stal::from_template(vec![b"SMEMBERS".to_vec(), vec![]], vec![(self.clone(), 1)]),
Union(ref sets) => ("SUNION", sets),
Inter(ref sets) => ("SINTER", sets),
Diff(ref sets) => ("SDIFF", sets),
};
let mut command = vec![op.as_bytes().to_vec()];
command.extend(sets.iter().map(|_| vec![]).collect::<Vec<_>>());
let mut setv = vec![];
for i in 0..sets.len() {
setv.push((sets[i].clone(), i + 1));
}
Stal::from_template(command, setv)
}
/// Maps the operation to its Redis command name.
fn
|
(&self) -> &'static str {
match *self {
Key(_) => unreachable!(),
Union(_) => "SUNIONSTORE",
Inter(_) => "SINTERSTORE",
Diff(_) => "SDIFFSTORE",
}
}
/// Appends the operation to `ops` and any temporary id created to `ids`.
/// Returns the key representing the set.
pub fn convert(&self, ids: &mut Vec<String>, ops: &mut Vec<Vec<Vec<u8>>>) -> Vec<u8> {
let sets = match *self {
Key(ref k) => return k.clone(),
Union(ref sets) => sets,
Inter(ref sets) => sets,
Diff(ref sets) => sets,
};
let mut op = Vec::with_capacity(2 + sets.len());
let id = format!("stal:{}", ids.len());
let r = id.as_bytes().to_vec();
ids.push(id);
op.push(self.command().as_bytes().to_vec());
op.push(r.clone());
op.extend(sets.into_iter().map(|s| s.convert(ids, ops)));
ops.push(op);
r
}
}
/// An operation to be executed on a set
#[derive(Debug)]
pub struct Stal {
/// A Redis command
command: Vec<Vec<u8>>,
/// Set in which execute the operation
sets: Vec<(Set, usize)>,
}
impl Stal {
pub fn new(operation: String, set: Set) -> Self {
Stal {
command: vec![operation.as_bytes().to_vec(), vec![]],
sets: vec![(set, 1)],
}
}
/// Takes an arbitrary command that uses one or more sets. The `command`
/// must have placeholders where the set keys should go. Each element
/// in `sets` specifies the position in the `command`.
pub fn from_template(command: Vec<Vec<u8>>, sets: Vec<(Set, usize)>) -> Self {
Stal {
command: command,
sets: sets,
}
}
fn add_ops(&self, ids: &mut Vec<String>, ops: &mut Vec<Vec<Vec<u8>>>) {
let mut command = self.command.clone();
for args in self.sets.iter() {
command.push(args.0.convert(ids, ops));
command.swap_remove(args.1);
}
ops.push(command);
}
/// Returns a list of operations to run. For debug only.
pub fn explain(&self) -> Vec<Vec<Vec<u8>>> {
let mut ids = vec![];
let mut ops = vec![];
self.add_ops(&mut ids, &mut ops);
ops
}
/// Returns a lit of operations, wrapped in a multi/exec.
/// The last operation is always exec, and the returned `usize` indicates
/// the return value of the `operation`.
pub fn solve(&self) -> (Vec<Vec<Vec<u8>>>, usize) {
let mut ids = vec![];
let mut ops = vec![vec![b"MULTI".to_vec()]];
self.add_ops(&mut ids, &mut ops);
let pos = ops.len() - 1;
if ids.len() > 0 {
let mut del = vec![b"DEL".to_vec()];
del.extend(ids.into_iter().map(|x| x.as_bytes().to_vec()));
ops.push(del);
}
ops.push(vec![b"EXEC".to_vec()]);
(ops, pos)
}
}
|
command
|
identifier_name
|
bluetoothdevice.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::BluetoothDeviceBinding;
use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root, MutHeap, MutNullableHeap};
use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::bluetoothadvertisingdata::BluetoothAdvertisingData;
use dom::bluetoothremotegattserver::BluetoothRemoteGATTServer;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdevice
#[dom_struct]
pub struct BluetoothDevice {
reflector_: Reflector,
id: DOMString,
name: Option<DOMString>,
adData: MutHeap<JS<BluetoothAdvertisingData>>,
gatt: MutNullableHeap<JS<BluetoothRemoteGATTServer>>,
}
impl BluetoothDevice {
pub fn new_inherited(id: DOMString,
name: Option<DOMString>,
adData: &BluetoothAdvertisingData)
-> BluetoothDevice
|
pub fn new(global: GlobalRef,
id: DOMString,
name: Option<DOMString>,
adData: &BluetoothAdvertisingData)
-> Root<BluetoothDevice> {
reflect_dom_object(box BluetoothDevice::new_inherited(id,
name,
adData),
global,
BluetoothDeviceBinding::Wrap)
}
}
impl BluetoothDeviceMethods for BluetoothDevice {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-id
fn Id(&self) -> DOMString {
self.id.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-name
fn GetName(&self) -> Option<DOMString> {
self.name.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-addata
fn AdData(&self) -> Root<BluetoothAdvertisingData> {
self.adData.get()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt
fn Gatt(&self) -> Root<BluetoothRemoteGATTServer> {
self.gatt.or_init(|| BluetoothRemoteGATTServer::new(self.global().r(), self))
}
}
|
{
BluetoothDevice {
reflector_: Reflector::new(),
id: id,
name: name,
adData: MutHeap::new(adData),
gatt: Default::default(),
}
}
|
identifier_body
|
bluetoothdevice.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::BluetoothDeviceBinding;
use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root, MutHeap, MutNullableHeap};
use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::bluetoothadvertisingdata::BluetoothAdvertisingData;
use dom::bluetoothremotegattserver::BluetoothRemoteGATTServer;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdevice
#[dom_struct]
pub struct BluetoothDevice {
reflector_: Reflector,
id: DOMString,
name: Option<DOMString>,
adData: MutHeap<JS<BluetoothAdvertisingData>>,
gatt: MutNullableHeap<JS<BluetoothRemoteGATTServer>>,
}
impl BluetoothDevice {
pub fn new_inherited(id: DOMString,
name: Option<DOMString>,
|
adData: &BluetoothAdvertisingData)
-> BluetoothDevice {
BluetoothDevice {
reflector_: Reflector::new(),
id: id,
name: name,
adData: MutHeap::new(adData),
gatt: Default::default(),
}
}
pub fn new(global: GlobalRef,
id: DOMString,
name: Option<DOMString>,
adData: &BluetoothAdvertisingData)
-> Root<BluetoothDevice> {
reflect_dom_object(box BluetoothDevice::new_inherited(id,
name,
adData),
global,
BluetoothDeviceBinding::Wrap)
}
}
impl BluetoothDeviceMethods for BluetoothDevice {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-id
fn Id(&self) -> DOMString {
self.id.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-name
fn GetName(&self) -> Option<DOMString> {
self.name.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-addata
fn AdData(&self) -> Root<BluetoothAdvertisingData> {
self.adData.get()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt
fn Gatt(&self) -> Root<BluetoothRemoteGATTServer> {
self.gatt.or_init(|| BluetoothRemoteGATTServer::new(self.global().r(), self))
}
}
|
random_line_split
|
|
bluetoothdevice.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::BluetoothDeviceBinding;
use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root, MutHeap, MutNullableHeap};
use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::bluetoothadvertisingdata::BluetoothAdvertisingData;
use dom::bluetoothremotegattserver::BluetoothRemoteGATTServer;
// https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdevice
#[dom_struct]
pub struct BluetoothDevice {
reflector_: Reflector,
id: DOMString,
name: Option<DOMString>,
adData: MutHeap<JS<BluetoothAdvertisingData>>,
gatt: MutNullableHeap<JS<BluetoothRemoteGATTServer>>,
}
impl BluetoothDevice {
pub fn
|
(id: DOMString,
name: Option<DOMString>,
adData: &BluetoothAdvertisingData)
-> BluetoothDevice {
BluetoothDevice {
reflector_: Reflector::new(),
id: id,
name: name,
adData: MutHeap::new(adData),
gatt: Default::default(),
}
}
pub fn new(global: GlobalRef,
id: DOMString,
name: Option<DOMString>,
adData: &BluetoothAdvertisingData)
-> Root<BluetoothDevice> {
reflect_dom_object(box BluetoothDevice::new_inherited(id,
name,
adData),
global,
BluetoothDeviceBinding::Wrap)
}
}
impl BluetoothDeviceMethods for BluetoothDevice {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-id
fn Id(&self) -> DOMString {
self.id.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-name
fn GetName(&self) -> Option<DOMString> {
self.name.clone()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-addata
fn AdData(&self) -> Root<BluetoothAdvertisingData> {
self.adData.get()
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt
fn Gatt(&self) -> Root<BluetoothRemoteGATTServer> {
self.gatt.or_init(|| BluetoothRemoteGATTServer::new(self.global().r(), self))
}
}
|
new_inherited
|
identifier_name
|
color.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Resolved color values.
use super::{Context, ToResolvedValue};
use crate::values::computed;
use crate::values::generics::color as generics;
impl ToResolvedValue for computed::Color {
// A resolved color value is an rgba color, with currentcolor resolved.
type ResolvedValue = cssparser::RGBA;
#[inline]
|
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
generics::Color::Numeric(resolved)
}
}
impl ToResolvedValue for computed::ColorOrAuto {
// A resolved caret-color value is an rgba color, with auto resolving to
// currentcolor.
type ResolvedValue = cssparser::RGBA;
#[inline]
fn to_resolved_value(self, context: &Context) -> Self::ResolvedValue {
let color = match self {
generics::ColorOrAuto::Color(color) => color,
generics::ColorOrAuto::Auto => generics::Color::CurrentColor,
};
color.to_resolved_value(context)
}
#[inline]
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
generics::ColorOrAuto::Color(computed::Color::from_resolved_value(resolved))
}
}
|
fn to_resolved_value(self, context: &Context) -> Self::ResolvedValue {
context.style.resolve_color(self)
}
#[inline]
|
random_line_split
|
color.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Resolved color values.
use super::{Context, ToResolvedValue};
use crate::values::computed;
use crate::values::generics::color as generics;
impl ToResolvedValue for computed::Color {
// A resolved color value is an rgba color, with currentcolor resolved.
type ResolvedValue = cssparser::RGBA;
#[inline]
fn
|
(self, context: &Context) -> Self::ResolvedValue {
context.style.resolve_color(self)
}
#[inline]
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
generics::Color::Numeric(resolved)
}
}
impl ToResolvedValue for computed::ColorOrAuto {
// A resolved caret-color value is an rgba color, with auto resolving to
// currentcolor.
type ResolvedValue = cssparser::RGBA;
#[inline]
fn to_resolved_value(self, context: &Context) -> Self::ResolvedValue {
let color = match self {
generics::ColorOrAuto::Color(color) => color,
generics::ColorOrAuto::Auto => generics::Color::CurrentColor,
};
color.to_resolved_value(context)
}
#[inline]
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
generics::ColorOrAuto::Color(computed::Color::from_resolved_value(resolved))
}
}
|
to_resolved_value
|
identifier_name
|
color.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Resolved color values.
use super::{Context, ToResolvedValue};
use crate::values::computed;
use crate::values::generics::color as generics;
impl ToResolvedValue for computed::Color {
// A resolved color value is an rgba color, with currentcolor resolved.
type ResolvedValue = cssparser::RGBA;
#[inline]
fn to_resolved_value(self, context: &Context) -> Self::ResolvedValue {
context.style.resolve_color(self)
}
#[inline]
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
generics::Color::Numeric(resolved)
}
}
impl ToResolvedValue for computed::ColorOrAuto {
// A resolved caret-color value is an rgba color, with auto resolving to
// currentcolor.
type ResolvedValue = cssparser::RGBA;
#[inline]
fn to_resolved_value(self, context: &Context) -> Self::ResolvedValue
|
#[inline]
fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
generics::ColorOrAuto::Color(computed::Color::from_resolved_value(resolved))
}
}
|
{
let color = match self {
generics::ColorOrAuto::Color(color) => color,
generics::ColorOrAuto::Auto => generics::Color::CurrentColor,
};
color.to_resolved_value(context)
}
|
identifier_body
|
main.rs
|
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate itertools;
extern crate regex;
extern crate rustc_serialize;
extern crate strsim;
extern crate telegram_bot as telegram;
extern crate term_painter;
#[macro_use]
mod log;
|
mod needed;
use bot::MartiniBot;
use log::LogLevel;
use std::env;
use std::path::Path;
fn main() {
// Fetch environment variable with bot token
let token = match env::var("TELEGRAM_BOT_TOKEN") {
Ok(tok) => tok,
Err(e) =>
panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {}", e),
};
// Create bot and print bot information, if it succeeded
let mut bot = MartiniBot::from_token(token)
.with_logfile(Path::new("log.txt"))
.with_loglevel(LogLevel::Debug)
.build()
.unwrap_or_else(|e| panic!("Error starting bot: {} \n{:?}", e, e));
let me = bot.me();
bot.log(LogLevel::Info, &*format!("Started bot: {:?}", me));
bot.run();
}
|
mod bot;
mod iter;
|
random_line_split
|
main.rs
|
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate itertools;
extern crate regex;
extern crate rustc_serialize;
extern crate strsim;
extern crate telegram_bot as telegram;
extern crate term_painter;
#[macro_use]
mod log;
mod bot;
mod iter;
mod needed;
use bot::MartiniBot;
use log::LogLevel;
use std::env;
use std::path::Path;
fn main()
|
{
// Fetch environment variable with bot token
let token = match env::var("TELEGRAM_BOT_TOKEN") {
Ok(tok) => tok,
Err(e) =>
panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {}", e),
};
// Create bot and print bot information, if it succeeded
let mut bot = MartiniBot::from_token(token)
.with_logfile(Path::new("log.txt"))
.with_loglevel(LogLevel::Debug)
.build()
.unwrap_or_else(|e| panic!("Error starting bot: {} \n{:?}", e, e));
let me = bot.me();
bot.log(LogLevel::Info, &*format!("Started bot: {:?}", me));
bot.run();
}
|
identifier_body
|
|
main.rs
|
#![feature(plugin)]
#![plugin(regex_macros)]
extern crate itertools;
extern crate regex;
extern crate rustc_serialize;
extern crate strsim;
extern crate telegram_bot as telegram;
extern crate term_painter;
#[macro_use]
mod log;
mod bot;
mod iter;
mod needed;
use bot::MartiniBot;
use log::LogLevel;
use std::env;
use std::path::Path;
fn
|
() {
// Fetch environment variable with bot token
let token = match env::var("TELEGRAM_BOT_TOKEN") {
Ok(tok) => tok,
Err(e) =>
panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {}", e),
};
// Create bot and print bot information, if it succeeded
let mut bot = MartiniBot::from_token(token)
.with_logfile(Path::new("log.txt"))
.with_loglevel(LogLevel::Debug)
.build()
.unwrap_or_else(|e| panic!("Error starting bot: {} \n{:?}", e, e));
let me = bot.me();
bot.log(LogLevel::Info, &*format!("Started bot: {:?}", me));
bot.run();
}
|
main
|
identifier_name
|
main.rs
|
use std::int;
use std::comm::stream;
use std::comm::Port;
use std::comm::Chan;
type MaybeInt = Option<int>;
fn fib_generator(max: int, chan: &Chan<MaybeInt>) {
let mut a = 0;
let mut b = 1;
loop {
let next = a + b;
if next > max {
break;
}
b = a;
a = next;
chan.send(Some(next));
}
chan.send(None);
}
fn main() {
let (port, chan): (Port<MaybeInt>, Chan<MaybeInt>) = stream();
do spawn {
fib_generator(4000000, &chan);
|
}
let mut accum: int = 0;
loop {
let next: MaybeInt = port.recv();
match next {
Some(x) if x % 2 == 0 => accum += x,
Some(_) => loop,
None => break,
};
}
println(fmt!("%d", accum));
}
|
random_line_split
|
|
main.rs
|
use std::int;
use std::comm::stream;
use std::comm::Port;
use std::comm::Chan;
type MaybeInt = Option<int>;
fn
|
(max: int, chan: &Chan<MaybeInt>) {
let mut a = 0;
let mut b = 1;
loop {
let next = a + b;
if next > max {
break;
}
b = a;
a = next;
chan.send(Some(next));
}
chan.send(None);
}
fn main() {
let (port, chan): (Port<MaybeInt>, Chan<MaybeInt>) = stream();
do spawn {
fib_generator(4000000, &chan);
}
let mut accum: int = 0;
loop {
let next: MaybeInt = port.recv();
match next {
Some(x) if x % 2 == 0 => accum += x,
Some(_) => loop,
None => break,
};
}
println(fmt!("%d", accum));
}
|
fib_generator
|
identifier_name
|
main.rs
|
use std::int;
use std::comm::stream;
use std::comm::Port;
use std::comm::Chan;
type MaybeInt = Option<int>;
fn fib_generator(max: int, chan: &Chan<MaybeInt>)
|
fn main() {
let (port, chan): (Port<MaybeInt>, Chan<MaybeInt>) = stream();
do spawn {
fib_generator(4000000, &chan);
}
let mut accum: int = 0;
loop {
let next: MaybeInt = port.recv();
match next {
Some(x) if x % 2 == 0 => accum += x,
Some(_) => loop,
None => break,
};
}
println(fmt!("%d", accum));
}
|
{
let mut a = 0;
let mut b = 1;
loop {
let next = a + b;
if next > max {
break;
}
b = a;
a = next;
chan.send(Some(next));
}
chan.send(None);
}
|
identifier_body
|
document_loader.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Tracking of pending loads in a document.
//!
//! <https://html.spec.whatwg.org/multipage/#the-end>
use crate::dom::bindings::root::Dom;
use crate::dom::document::Document;
use crate::fetch::FetchCanceller;
use ipc_channel::ipc::IpcSender;
use net_traits::request::RequestBuilder;
use net_traits::{CoreResourceMsg, FetchChannels, FetchResponseMsg};
use net_traits::{IpcSend, ResourceThreads};
use servo_url::ServoUrl;
#[derive(Clone, Debug, JSTraceable, MallocSizeOf, PartialEq)]
pub enum LoadType {
Image(ServoUrl),
Script(ServoUrl),
Subframe(ServoUrl),
Stylesheet(ServoUrl),
PageSource(ServoUrl),
Media,
}
/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
/// created via DocumentLoader::fetch_async) are always removed by the time
/// that the owner is destroyed.
#[derive(JSTraceable, MallocSizeOf)]
#[unrooted_must_root_lint::must_root]
pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: Dom<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.loader_mut().add_blocking_load(load.clone());
LoadBlocker {
doc: Dom::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &mut Option<LoadBlocker>) {
if let Some(this) = blocker.as_mut() {
this.doc.finish_load(this.load.take().unwrap());
}
*blocker = None;
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
if let Some(load) = self.load.take() {
self.doc.finish_load(load);
}
}
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct DocumentLoader {
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
events_inhibited: bool,
cancellers: Vec<FetchCanceller>,
}
impl DocumentLoader {
pub fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(
resource_threads: ResourceThreads,
initial_load: Option<ServoUrl>,
) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
DocumentLoader {
resource_threads: resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
cancellers: Vec::new(),
}
}
pub fn cancel_all_loads(&mut self) -> bool {
|
// Associated fetches will be canceled when dropping the canceller.
self.cancellers.clear();
canceled_any
}
/// Add a load to the list of blocking loads.
fn add_blocking_load(&mut self, load: LoadType) {
debug!(
"Adding blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
self.blocking_loads.push(load);
}
/// Initiate a new fetch.
pub fn fetch_async(
&mut self,
load: LoadType,
request: RequestBuilder,
fetch_target: IpcSender<FetchResponseMsg>,
) {
self.add_blocking_load(load);
self.fetch_async_background(request, fetch_target);
}
/// Initiate a new fetch that does not block the document load event.
pub fn fetch_async_background(
&mut self,
request: RequestBuilder,
fetch_target: IpcSender<FetchResponseMsg>,
) {
let mut canceller = FetchCanceller::new();
let cancel_receiver = canceller.initialize();
self.cancellers.push(canceller);
self.resource_threads
.sender()
.send(CoreResourceMsg::Fetch(
request,
FetchChannels::ResponseMsg(fetch_target, Some(cancel_receiver)),
))
.unwrap();
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
debug!(
"Removing blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
let idx = self
.blocking_loads
.iter()
.position(|unfinished| *unfinished == *load);
match idx {
Some(i) => {
self.blocking_loads.remove(i);
},
None => warn!("unknown completed load {:?}", load),
}
}
pub fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn is_only_blocked_by_iframes(&self) -> bool {
self.blocking_loads.iter().all(|load| match *load {
LoadType::Subframe(_) => true,
_ => false,
})
}
pub fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}
|
let canceled_any = !self.cancellers.is_empty();
|
random_line_split
|
document_loader.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Tracking of pending loads in a document.
//!
//! <https://html.spec.whatwg.org/multipage/#the-end>
use crate::dom::bindings::root::Dom;
use crate::dom::document::Document;
use crate::fetch::FetchCanceller;
use ipc_channel::ipc::IpcSender;
use net_traits::request::RequestBuilder;
use net_traits::{CoreResourceMsg, FetchChannels, FetchResponseMsg};
use net_traits::{IpcSend, ResourceThreads};
use servo_url::ServoUrl;
#[derive(Clone, Debug, JSTraceable, MallocSizeOf, PartialEq)]
pub enum LoadType {
Image(ServoUrl),
Script(ServoUrl),
Subframe(ServoUrl),
Stylesheet(ServoUrl),
PageSource(ServoUrl),
Media,
}
/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
/// created via DocumentLoader::fetch_async) are always removed by the time
/// that the owner is destroyed.
#[derive(JSTraceable, MallocSizeOf)]
#[unrooted_must_root_lint::must_root]
pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: Dom<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.loader_mut().add_blocking_load(load.clone());
LoadBlocker {
doc: Dom::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &mut Option<LoadBlocker>) {
if let Some(this) = blocker.as_mut() {
this.doc.finish_load(this.load.take().unwrap());
}
*blocker = None;
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
if let Some(load) = self.load.take() {
self.doc.finish_load(load);
}
}
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct DocumentLoader {
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
events_inhibited: bool,
cancellers: Vec<FetchCanceller>,
}
impl DocumentLoader {
pub fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(
resource_threads: ResourceThreads,
initial_load: Option<ServoUrl>,
) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
DocumentLoader {
resource_threads: resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
cancellers: Vec::new(),
}
}
pub fn cancel_all_loads(&mut self) -> bool {
let canceled_any =!self.cancellers.is_empty();
// Associated fetches will be canceled when dropping the canceller.
self.cancellers.clear();
canceled_any
}
/// Add a load to the list of blocking loads.
fn add_blocking_load(&mut self, load: LoadType) {
debug!(
"Adding blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
self.blocking_loads.push(load);
}
/// Initiate a new fetch.
pub fn fetch_async(
&mut self,
load: LoadType,
request: RequestBuilder,
fetch_target: IpcSender<FetchResponseMsg>,
) {
self.add_blocking_load(load);
self.fetch_async_background(request, fetch_target);
}
/// Initiate a new fetch that does not block the document load event.
pub fn fetch_async_background(
&mut self,
request: RequestBuilder,
fetch_target: IpcSender<FetchResponseMsg>,
) {
let mut canceller = FetchCanceller::new();
let cancel_receiver = canceller.initialize();
self.cancellers.push(canceller);
self.resource_threads
.sender()
.send(CoreResourceMsg::Fetch(
request,
FetchChannels::ResponseMsg(fetch_target, Some(cancel_receiver)),
))
.unwrap();
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
debug!(
"Removing blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
let idx = self
.blocking_loads
.iter()
.position(|unfinished| *unfinished == *load);
match idx {
Some(i) => {
self.blocking_loads.remove(i);
},
None => warn!("unknown completed load {:?}", load),
}
}
pub fn
|
(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn is_only_blocked_by_iframes(&self) -> bool {
self.blocking_loads.iter().all(|load| match *load {
LoadType::Subframe(_) => true,
_ => false,
})
}
pub fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}
|
is_blocked
|
identifier_name
|
document_loader.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Tracking of pending loads in a document.
//!
//! <https://html.spec.whatwg.org/multipage/#the-end>
use crate::dom::bindings::root::Dom;
use crate::dom::document::Document;
use crate::fetch::FetchCanceller;
use ipc_channel::ipc::IpcSender;
use net_traits::request::RequestBuilder;
use net_traits::{CoreResourceMsg, FetchChannels, FetchResponseMsg};
use net_traits::{IpcSend, ResourceThreads};
use servo_url::ServoUrl;
#[derive(Clone, Debug, JSTraceable, MallocSizeOf, PartialEq)]
pub enum LoadType {
Image(ServoUrl),
Script(ServoUrl),
Subframe(ServoUrl),
Stylesheet(ServoUrl),
PageSource(ServoUrl),
Media,
}
/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
/// created via DocumentLoader::fetch_async) are always removed by the time
/// that the owner is destroyed.
#[derive(JSTraceable, MallocSizeOf)]
#[unrooted_must_root_lint::must_root]
pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing.
doc: Dom<Document>,
/// The load that is blocking the document's load event.
load: Option<LoadType>,
}
impl LoadBlocker {
/// Mark the document's load event as blocked on this new load.
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.loader_mut().add_blocking_load(load.clone());
LoadBlocker {
doc: Dom::from_ref(doc),
load: Some(load),
}
}
/// Remove this load from the associated document's list of blocking loads.
pub fn terminate(blocker: &mut Option<LoadBlocker>) {
if let Some(this) = blocker.as_mut() {
this.doc.finish_load(this.load.take().unwrap());
}
*blocker = None;
}
}
impl Drop for LoadBlocker {
fn drop(&mut self) {
if let Some(load) = self.load.take()
|
}
}
#[derive(JSTraceable, MallocSizeOf)]
pub struct DocumentLoader {
resource_threads: ResourceThreads,
blocking_loads: Vec<LoadType>,
events_inhibited: bool,
cancellers: Vec<FetchCanceller>,
}
impl DocumentLoader {
pub fn new(existing: &DocumentLoader) -> DocumentLoader {
DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
}
pub fn new_with_threads(
resource_threads: ResourceThreads,
initial_load: Option<ServoUrl>,
) -> DocumentLoader {
debug!("Initial blocking load {:?}.", initial_load);
let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
DocumentLoader {
resource_threads: resource_threads,
blocking_loads: initial_loads,
events_inhibited: false,
cancellers: Vec::new(),
}
}
pub fn cancel_all_loads(&mut self) -> bool {
let canceled_any =!self.cancellers.is_empty();
// Associated fetches will be canceled when dropping the canceller.
self.cancellers.clear();
canceled_any
}
/// Add a load to the list of blocking loads.
fn add_blocking_load(&mut self, load: LoadType) {
debug!(
"Adding blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
self.blocking_loads.push(load);
}
/// Initiate a new fetch.
pub fn fetch_async(
&mut self,
load: LoadType,
request: RequestBuilder,
fetch_target: IpcSender<FetchResponseMsg>,
) {
self.add_blocking_load(load);
self.fetch_async_background(request, fetch_target);
}
/// Initiate a new fetch that does not block the document load event.
pub fn fetch_async_background(
&mut self,
request: RequestBuilder,
fetch_target: IpcSender<FetchResponseMsg>,
) {
let mut canceller = FetchCanceller::new();
let cancel_receiver = canceller.initialize();
self.cancellers.push(canceller);
self.resource_threads
.sender()
.send(CoreResourceMsg::Fetch(
request,
FetchChannels::ResponseMsg(fetch_target, Some(cancel_receiver)),
))
.unwrap();
}
/// Mark an in-progress network request complete.
pub fn finish_load(&mut self, load: &LoadType) {
debug!(
"Removing blocking load {:?} ({}).",
load,
self.blocking_loads.len()
);
let idx = self
.blocking_loads
.iter()
.position(|unfinished| *unfinished == *load);
match idx {
Some(i) => {
self.blocking_loads.remove(i);
},
None => warn!("unknown completed load {:?}", load),
}
}
pub fn is_blocked(&self) -> bool {
// TODO: Ensure that we report blocked if parsing is still ongoing.
!self.blocking_loads.is_empty()
}
pub fn is_only_blocked_by_iframes(&self) -> bool {
self.blocking_loads.iter().all(|load| match *load {
LoadType::Subframe(_) => true,
_ => false,
})
}
pub fn inhibit_events(&mut self) {
self.events_inhibited = true;
}
pub fn events_inhibited(&self) -> bool {
self.events_inhibited
}
pub fn resource_threads(&self) -> &ResourceThreads {
&self.resource_threads
}
}
|
{
self.doc.finish_load(load);
}
|
conditional_block
|
namespaces.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 std::hashmap::HashMap;
use cssparser::*;
use errors::log_css_error;
pub struct NamespaceMap {
default: Option<~str>, // Optional URL
prefix_map: HashMap<~str, ~str>, // prefix -> URL
}
impl NamespaceMap {
pub fn new() -> NamespaceMap {
NamespaceMap { default: None, prefix_map: HashMap::new() }
}
}
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap)
|
url = Some(value);
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, url) {
(Some(prefix), Some(url)) => {
if namespaces.prefix_map.swap(prefix, url).is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
},
(None, Some(url)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(url);
},
_ => syntax_error!()
}
}
|
{
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some() { syntax_error!() }
let mut prefix: Option<~str> = None;
let mut url: Option<~str> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value);
},
URL(value) | String(value) => {
if url.is_some() { syntax_error!() }
|
identifier_body
|
namespaces.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 std::hashmap::HashMap;
use cssparser::*;
use errors::log_css_error;
pub struct NamespaceMap {
default: Option<~str>, // Optional URL
prefix_map: HashMap<~str, ~str>, // prefix -> URL
}
impl NamespaceMap {
pub fn
|
() -> NamespaceMap {
NamespaceMap { default: None, prefix_map: HashMap::new() }
}
}
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some() { syntax_error!() }
let mut prefix: Option<~str> = None;
let mut url: Option<~str> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value);
},
URL(value) | String(value) => {
if url.is_some() { syntax_error!() }
url = Some(value);
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, url) {
(Some(prefix), Some(url)) => {
if namespaces.prefix_map.swap(prefix, url).is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
},
(None, Some(url)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(url);
},
_ => syntax_error!()
}
}
|
new
|
identifier_name
|
namespaces.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 std::hashmap::HashMap;
use cssparser::*;
use errors::log_css_error;
pub struct NamespaceMap {
default: Option<~str>, // Optional URL
prefix_map: HashMap<~str, ~str>, // prefix -> URL
}
impl NamespaceMap {
pub fn new() -> NamespaceMap {
NamespaceMap { default: None, prefix_map: HashMap::new() }
}
}
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some()
|
let mut prefix: Option<~str> = None;
let mut url: Option<~str> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value);
},
URL(value) | String(value) => {
if url.is_some() { syntax_error!() }
url = Some(value);
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, url) {
(Some(prefix), Some(url)) => {
if namespaces.prefix_map.swap(prefix, url).is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
},
(None, Some(url)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(url);
},
_ => syntax_error!()
}
}
|
{ syntax_error!() }
|
conditional_block
|
namespaces.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 std::hashmap::HashMap;
use cssparser::*;
use errors::log_css_error;
pub struct NamespaceMap {
default: Option<~str>, // Optional URL
prefix_map: HashMap<~str, ~str>, // prefix -> URL
}
impl NamespaceMap {
pub fn new() -> NamespaceMap {
NamespaceMap { default: None, prefix_map: HashMap::new() }
}
}
|
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some() { syntax_error!() }
let mut prefix: Option<~str> = None;
let mut url: Option<~str> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value);
},
URL(value) | String(value) => {
if url.is_some() { syntax_error!() }
url = Some(value);
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, url) {
(Some(prefix), Some(url)) => {
if namespaces.prefix_map.swap(prefix, url).is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
},
(None, Some(url)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(url);
},
_ => syntax_error!()
}
}
|
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
|
random_line_split
|
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTArrayHeader};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::slice;
impl<T> Deref for nsTArray<T> {
type Target = [T];
fn deref<'a>(&'a self) -> &'a [T] {
unsafe { slice::from_raw_parts(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> DerefMut for nsTArray<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut [T] {
unsafe { slice::from_raw_parts_mut(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> nsTArray<T> {
#[inline]
fn header<'a>(&'a self) -> &'a nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
unsafe { mem::transmute(self.mBuffer) }
}
// unsafe, since header may be in shared static or something
unsafe fn header_mut<'a>(&'a mut self) -> &'a mut nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
mem::transmute(self.mBuffer)
}
#[inline]
unsafe fn slice_begin(&self) -> *mut T {
debug_assert!(!self.mBuffer.is_null());
(self.mBuffer as *const nsTArrayHeader).offset(1) as *mut _
}
/// Ensures the array has enough capacity at least to hold `cap` elements.
///
/// NOTE: This doesn't call the constructor on the values!
pub fn ensure_capacity(&mut self, cap: usize) {
if cap >= self.len() {
unsafe {
|
cap,
mem::size_of::<T>(),
)
}
}
}
/// Clears the array storage without calling the destructor on the values.
#[inline]
pub unsafe fn clear(&mut self) {
if self.len()!= 0 {
bindings::Gecko_ClearPODTArray(
self as *mut nsTArray<T> as *mut _,
mem::size_of::<T>(),
mem::align_of::<T>(),
);
}
}
/// Clears a POD array. This is safe since copy types are memcopyable.
#[inline]
pub fn clear_pod(&mut self)
where
T: Copy,
{
unsafe { self.clear() }
}
/// Resize and set the length of the array to `len`.
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not call constructors. If you need that, either manually add
/// bindings or run the typed `EnsureCapacity` call on the gecko side.
pub unsafe fn set_len(&mut self, len: u32) {
// this can leak
debug_assert!(len >= self.len() as u32);
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Resizes an array containing only POD elements
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not leak since it only works on POD types (and thus doesn't assert)
pub unsafe fn set_len_pod(&mut self, len: u32)
where
T: Copy,
{
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Collects the given iterator into this array.
///
/// Not unsafe because we won't leave uninitialized elements in the array.
pub fn assign_from_iter_pod<I>(&mut self, iter: I)
where
T: Copy,
I: ExactSizeIterator + Iterator<Item = T>,
{
debug_assert!(iter.len() <= 0xFFFFFFFF);
unsafe {
self.set_len_pod(iter.len() as u32);
}
self.iter_mut().zip(iter).for_each(|(r, v)| *r = v);
}
}
|
bindings::Gecko_EnsureTArrayCapacity(
self as *mut nsTArray<T> as *mut _,
|
random_line_split
|
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTArrayHeader};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::slice;
impl<T> Deref for nsTArray<T> {
type Target = [T];
fn deref<'a>(&'a self) -> &'a [T] {
unsafe { slice::from_raw_parts(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> DerefMut for nsTArray<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut [T] {
unsafe { slice::from_raw_parts_mut(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> nsTArray<T> {
#[inline]
fn header<'a>(&'a self) -> &'a nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
unsafe { mem::transmute(self.mBuffer) }
}
// unsafe, since header may be in shared static or something
unsafe fn header_mut<'a>(&'a mut self) -> &'a mut nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
mem::transmute(self.mBuffer)
}
#[inline]
unsafe fn slice_begin(&self) -> *mut T {
debug_assert!(!self.mBuffer.is_null());
(self.mBuffer as *const nsTArrayHeader).offset(1) as *mut _
}
/// Ensures the array has enough capacity at least to hold `cap` elements.
///
/// NOTE: This doesn't call the constructor on the values!
pub fn ensure_capacity(&mut self, cap: usize) {
if cap >= self.len() {
unsafe {
bindings::Gecko_EnsureTArrayCapacity(
self as *mut nsTArray<T> as *mut _,
cap,
mem::size_of::<T>(),
)
}
}
}
/// Clears the array storage without calling the destructor on the values.
#[inline]
pub unsafe fn clear(&mut self) {
if self.len()!= 0 {
bindings::Gecko_ClearPODTArray(
self as *mut nsTArray<T> as *mut _,
mem::size_of::<T>(),
mem::align_of::<T>(),
);
}
}
/// Clears a POD array. This is safe since copy types are memcopyable.
#[inline]
pub fn clear_pod(&mut self)
where
T: Copy,
|
/// Resize and set the length of the array to `len`.
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not call constructors. If you need that, either manually add
/// bindings or run the typed `EnsureCapacity` call on the gecko side.
pub unsafe fn set_len(&mut self, len: u32) {
// this can leak
debug_assert!(len >= self.len() as u32);
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Resizes an array containing only POD elements
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not leak since it only works on POD types (and thus doesn't assert)
pub unsafe fn set_len_pod(&mut self, len: u32)
where
T: Copy,
{
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Collects the given iterator into this array.
///
/// Not unsafe because we won't leave uninitialized elements in the array.
pub fn assign_from_iter_pod<I>(&mut self, iter: I)
where
T: Copy,
I: ExactSizeIterator + Iterator<Item = T>,
{
debug_assert!(iter.len() <= 0xFFFFFFFF);
unsafe {
self.set_len_pod(iter.len() as u32);
}
self.iter_mut().zip(iter).for_each(|(r, v)| *r = v);
}
}
|
{
unsafe { self.clear() }
}
|
identifier_body
|
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTArrayHeader};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::slice;
impl<T> Deref for nsTArray<T> {
type Target = [T];
fn deref<'a>(&'a self) -> &'a [T] {
unsafe { slice::from_raw_parts(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> DerefMut for nsTArray<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut [T] {
unsafe { slice::from_raw_parts_mut(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> nsTArray<T> {
#[inline]
fn header<'a>(&'a self) -> &'a nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
unsafe { mem::transmute(self.mBuffer) }
}
// unsafe, since header may be in shared static or something
unsafe fn header_mut<'a>(&'a mut self) -> &'a mut nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
mem::transmute(self.mBuffer)
}
#[inline]
unsafe fn slice_begin(&self) -> *mut T {
debug_assert!(!self.mBuffer.is_null());
(self.mBuffer as *const nsTArrayHeader).offset(1) as *mut _
}
/// Ensures the array has enough capacity at least to hold `cap` elements.
///
/// NOTE: This doesn't call the constructor on the values!
pub fn ensure_capacity(&mut self, cap: usize) {
if cap >= self.len() {
unsafe {
bindings::Gecko_EnsureTArrayCapacity(
self as *mut nsTArray<T> as *mut _,
cap,
mem::size_of::<T>(),
)
}
}
}
/// Clears the array storage without calling the destructor on the values.
#[inline]
pub unsafe fn clear(&mut self) {
if self.len()!= 0 {
bindings::Gecko_ClearPODTArray(
self as *mut nsTArray<T> as *mut _,
mem::size_of::<T>(),
mem::align_of::<T>(),
);
}
}
/// Clears a POD array. This is safe since copy types are memcopyable.
#[inline]
pub fn clear_pod(&mut self)
where
T: Copy,
{
unsafe { self.clear() }
}
/// Resize and set the length of the array to `len`.
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not call constructors. If you need that, either manually add
/// bindings or run the typed `EnsureCapacity` call on the gecko side.
pub unsafe fn set_len(&mut self, len: u32) {
// this can leak
debug_assert!(len >= self.len() as u32);
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Resizes an array containing only POD elements
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not leak since it only works on POD types (and thus doesn't assert)
pub unsafe fn
|
(&mut self, len: u32)
where
T: Copy,
{
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Collects the given iterator into this array.
///
/// Not unsafe because we won't leave uninitialized elements in the array.
pub fn assign_from_iter_pod<I>(&mut self, iter: I)
where
T: Copy,
I: ExactSizeIterator + Iterator<Item = T>,
{
debug_assert!(iter.len() <= 0xFFFFFFFF);
unsafe {
self.set_len_pod(iter.len() as u32);
}
self.iter_mut().zip(iter).for_each(|(r, v)| *r = v);
}
}
|
set_len_pod
|
identifier_name
|
ns_t_array.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/. */
//! Rust helpers for Gecko's nsTArray.
use gecko_bindings::bindings;
use gecko_bindings::structs::{nsTArray, nsTArrayHeader};
use std::mem;
use std::ops::{Deref, DerefMut};
use std::slice;
impl<T> Deref for nsTArray<T> {
type Target = [T];
fn deref<'a>(&'a self) -> &'a [T] {
unsafe { slice::from_raw_parts(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> DerefMut for nsTArray<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut [T] {
unsafe { slice::from_raw_parts_mut(self.slice_begin(), self.header().mLength as usize) }
}
}
impl<T> nsTArray<T> {
#[inline]
fn header<'a>(&'a self) -> &'a nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
unsafe { mem::transmute(self.mBuffer) }
}
// unsafe, since header may be in shared static or something
unsafe fn header_mut<'a>(&'a mut self) -> &'a mut nsTArrayHeader {
debug_assert!(!self.mBuffer.is_null());
mem::transmute(self.mBuffer)
}
#[inline]
unsafe fn slice_begin(&self) -> *mut T {
debug_assert!(!self.mBuffer.is_null());
(self.mBuffer as *const nsTArrayHeader).offset(1) as *mut _
}
/// Ensures the array has enough capacity at least to hold `cap` elements.
///
/// NOTE: This doesn't call the constructor on the values!
pub fn ensure_capacity(&mut self, cap: usize) {
if cap >= self.len() {
unsafe {
bindings::Gecko_EnsureTArrayCapacity(
self as *mut nsTArray<T> as *mut _,
cap,
mem::size_of::<T>(),
)
}
}
}
/// Clears the array storage without calling the destructor on the values.
#[inline]
pub unsafe fn clear(&mut self) {
if self.len()!= 0
|
}
/// Clears a POD array. This is safe since copy types are memcopyable.
#[inline]
pub fn clear_pod(&mut self)
where
T: Copy,
{
unsafe { self.clear() }
}
/// Resize and set the length of the array to `len`.
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not call constructors. If you need that, either manually add
/// bindings or run the typed `EnsureCapacity` call on the gecko side.
pub unsafe fn set_len(&mut self, len: u32) {
// this can leak
debug_assert!(len >= self.len() as u32);
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Resizes an array containing only POD elements
///
/// unsafe because this may leave the array with uninitialized elements.
///
/// This will not leak since it only works on POD types (and thus doesn't assert)
pub unsafe fn set_len_pod(&mut self, len: u32)
where
T: Copy,
{
self.ensure_capacity(len as usize);
let header = self.header_mut();
header.mLength = len;
}
/// Collects the given iterator into this array.
///
/// Not unsafe because we won't leave uninitialized elements in the array.
pub fn assign_from_iter_pod<I>(&mut self, iter: I)
where
T: Copy,
I: ExactSizeIterator + Iterator<Item = T>,
{
debug_assert!(iter.len() <= 0xFFFFFFFF);
unsafe {
self.set_len_pod(iter.len() as u32);
}
self.iter_mut().zip(iter).for_each(|(r, v)| *r = v);
}
}
|
{
bindings::Gecko_ClearPODTArray(
self as *mut nsTArray<T> as *mut _,
mem::size_of::<T>(),
mem::align_of::<T>(),
);
}
|
conditional_block
|
credentials.rs
|
#[macro_use]
extern crate accord;
use accord::{Accord, Result as AccordResult};
use accord::validators::{length, contains, not_contain_any};
struct Credentials {
pub email: String,
pub password: String,
}
impl Accord for Credentials {
#[cfg(not(feature = "inclusive_range"))]
fn validate(&self) -> AccordResult {
rules!{
"email" => self.email => [length(5, 64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
}
#[cfg(feature = "inclusive_range")]
fn
|
(&self) -> AccordResult {
rules!{
"email" => self.email => [length(5..=64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
}
}
#[test]
fn main() {
let a = Credentials {
email: "[email protected]".to_string(),
password: "lfdsfsfsfghdgdljddsjfkdlsf".to_string(),
};
let b = Credentials {
email: "t".to_string(),
password: "admin1234password".to_string(),
};
assert!(a.validate().is_ok());
assert!(b.validate().is_err());
}
|
validate
|
identifier_name
|
credentials.rs
|
#[macro_use]
extern crate accord;
use accord::{Accord, Result as AccordResult};
use accord::validators::{length, contains, not_contain_any};
struct Credentials {
pub email: String,
pub password: String,
}
impl Accord for Credentials {
#[cfg(not(feature = "inclusive_range"))]
fn validate(&self) -> AccordResult {
rules!{
"email" => self.email => [length(5, 64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
}
#[cfg(feature = "inclusive_range")]
fn validate(&self) -> AccordResult
|
}
#[test]
fn main() {
let a = Credentials {
email: "[email protected]".to_string(),
password: "lfdsfsfsfghdgdljddsjfkdlsf".to_string(),
};
let b = Credentials {
email: "t".to_string(),
password: "admin1234password".to_string(),
};
assert!(a.validate().is_ok());
assert!(b.validate().is_err());
}
|
{
rules!{
"email" => self.email => [length(5..=64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
}
|
identifier_body
|
credentials.rs
|
#[macro_use]
extern crate accord;
use accord::{Accord, Result as AccordResult};
|
pub password: String,
}
impl Accord for Credentials {
#[cfg(not(feature = "inclusive_range"))]
fn validate(&self) -> AccordResult {
rules!{
"email" => self.email => [length(5, 64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
}
#[cfg(feature = "inclusive_range")]
fn validate(&self) -> AccordResult {
rules!{
"email" => self.email => [length(5..=64), contains("@"), contains(".")],
"password" => self.password => [not_contain_any(&["1234", "admin", "password"])]
}
}
}
#[test]
fn main() {
let a = Credentials {
email: "[email protected]".to_string(),
password: "lfdsfsfsfghdgdljddsjfkdlsf".to_string(),
};
let b = Credentials {
email: "t".to_string(),
password: "admin1234password".to_string(),
};
assert!(a.validate().is_ok());
assert!(b.validate().is_err());
}
|
use accord::validators::{length, contains, not_contain_any};
struct Credentials {
pub email: String,
|
random_line_split
|
p13.rs
|
use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()> {
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (items.next(), items.next(), items.next()) {
(Some(key), Some(val), None) => {
obj.insert(key.to_string(), Json::String(val.to_string()));
},
_ =>
|
};
}
Ok(Json::Object(obj))
}
#[test]
fn test_parse_queryst() {
let json = parse_querystr("foo=bar&[email protected]").unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["foo"], "bar".to_json());
assert_eq!(obj["baz"], "[email protected]".to_json());
}
fn profile_for(email: &str) -> String {
let email_clean = email.replace(|c| c == '=' || c == '&', "");
format!("email={}&uid={}&role=user", email_clean, 10)
}
fn encryption_oracle(key: &[u8], input: &str) -> Vec<u8> {
let plaintext = profile_for(input);
let data = plaintext.as_bytes();
encrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap()
}
fn decryption_oracle(key: &[u8], data: &[u8]) -> Json {
let plaintext = decrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap();
let string = String::from_utf8_lossy(&plaintext);
parse_querystr(&string).unwrap()
}
#[test]
fn run() {
let blocksize = 16;
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// 0123456789012345|0123456789012345|0123456789012345|012345678912345
// email=AAAAAAAAAA|adminPPPPPPPPPPP|AAA&uid=10&role=|userPPPPPPPPPPP
// ^^^^^^^^^^|^^^^^^^^^^^^^^^^|^^^
// input
let input = "AAAAAAAAAAadmin\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0bAAA";
let mut ciphertext = encryption_oracle(&key, input);
// substitute the block with admin text in it to make an admin profile!
let admin_block = &ciphertext[1*blocksize..2*blocksize].to_vec();
&mut ciphertext[3*blocksize..4*blocksize].copy_from_slice(&admin_block);
let json = decryption_oracle(&key, &ciphertext);
let obj = json.as_object().unwrap();
assert_eq!(obj["role"], "admin".to_json());
}
|
{
return Err(());
}
|
conditional_block
|
p13.rs
|
use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()> {
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (items.next(), items.next(), items.next()) {
(Some(key), Some(val), None) => {
obj.insert(key.to_string(), Json::String(val.to_string()));
},
_ => {
return Err(());
}
};
}
Ok(Json::Object(obj))
}
#[test]
fn test_parse_queryst() {
let json = parse_querystr("foo=bar&[email protected]").unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["foo"], "bar".to_json());
assert_eq!(obj["baz"], "[email protected]".to_json());
}
fn profile_for(email: &str) -> String {
let email_clean = email.replace(|c| c == '=' || c == '&', "");
format!("email={}&uid={}&role=user", email_clean, 10)
}
fn encryption_oracle(key: &[u8], input: &str) -> Vec<u8> {
let plaintext = profile_for(input);
let data = plaintext.as_bytes();
encrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap()
}
fn decryption_oracle(key: &[u8], data: &[u8]) -> Json {
let plaintext = decrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap();
let string = String::from_utf8_lossy(&plaintext);
parse_querystr(&string).unwrap()
}
#[test]
fn run() {
|
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// 0123456789012345|0123456789012345|0123456789012345|012345678912345
// email=AAAAAAAAAA|adminPPPPPPPPPPP|AAA&uid=10&role=|userPPPPPPPPPPP
// ^^^^^^^^^^|^^^^^^^^^^^^^^^^|^^^
// input
let input = "AAAAAAAAAAadmin\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0bAAA";
let mut ciphertext = encryption_oracle(&key, input);
// substitute the block with admin text in it to make an admin profile!
let admin_block = &ciphertext[1*blocksize..2*blocksize].to_vec();
&mut ciphertext[3*blocksize..4*blocksize].copy_from_slice(&admin_block);
let json = decryption_oracle(&key, &ciphertext);
let obj = json.as_object().unwrap();
assert_eq!(obj["role"], "admin".to_json());
}
|
let blocksize = 16;
|
random_line_split
|
p13.rs
|
use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()> {
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (items.next(), items.next(), items.next()) {
(Some(key), Some(val), None) => {
obj.insert(key.to_string(), Json::String(val.to_string()));
},
_ => {
return Err(());
}
};
}
Ok(Json::Object(obj))
}
#[test]
fn test_parse_queryst() {
let json = parse_querystr("foo=bar&[email protected]").unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["foo"], "bar".to_json());
assert_eq!(obj["baz"], "[email protected]".to_json());
}
fn profile_for(email: &str) -> String {
let email_clean = email.replace(|c| c == '=' || c == '&', "");
format!("email={}&uid={}&role=user", email_clean, 10)
}
fn
|
(key: &[u8], input: &str) -> Vec<u8> {
let plaintext = profile_for(input);
let data = plaintext.as_bytes();
encrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap()
}
fn decryption_oracle(key: &[u8], data: &[u8]) -> Json {
let plaintext = decrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap();
let string = String::from_utf8_lossy(&plaintext);
parse_querystr(&string).unwrap()
}
#[test]
fn run() {
let blocksize = 16;
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// 0123456789012345|0123456789012345|0123456789012345|012345678912345
// email=AAAAAAAAAA|adminPPPPPPPPPPP|AAA&uid=10&role=|userPPPPPPPPPPP
// ^^^^^^^^^^|^^^^^^^^^^^^^^^^|^^^
// input
let input = "AAAAAAAAAAadmin\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0bAAA";
let mut ciphertext = encryption_oracle(&key, input);
// substitute the block with admin text in it to make an admin profile!
let admin_block = &ciphertext[1*blocksize..2*blocksize].to_vec();
&mut ciphertext[3*blocksize..4*blocksize].copy_from_slice(&admin_block);
let json = decryption_oracle(&key, &ciphertext);
let obj = json.as_object().unwrap();
assert_eq!(obj["role"], "admin".to_json());
}
|
encryption_oracle
|
identifier_name
|
p13.rs
|
use std::collections::BTreeMap;
use rand::{Rng, weak_rng};
use serialize::json::{Json, ToJson};
use ssl::symm::{self, encrypt, decrypt};
fn parse_querystr(input: &str) -> Result<Json, ()>
|
#[test]
fn test_parse_queryst() {
let json = parse_querystr("foo=bar&[email protected]").unwrap();
let obj = json.as_object().unwrap();
assert_eq!(obj["foo"], "bar".to_json());
assert_eq!(obj["baz"], "[email protected]".to_json());
}
fn profile_for(email: &str) -> String {
let email_clean = email.replace(|c| c == '=' || c == '&', "");
format!("email={}&uid={}&role=user", email_clean, 10)
}
fn encryption_oracle(key: &[u8], input: &str) -> Vec<u8> {
let plaintext = profile_for(input);
let data = plaintext.as_bytes();
encrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap()
}
fn decryption_oracle(key: &[u8], data: &[u8]) -> Json {
let plaintext = decrypt(symm::Cipher::aes_128_ecb(), key, None, data).unwrap();
let string = String::from_utf8_lossy(&plaintext);
parse_querystr(&string).unwrap()
}
#[test]
fn run() {
let blocksize = 16;
let mut rng = weak_rng();
let mut key = [0_u8; 16];
rng.fill_bytes(&mut key);
// 0123456789012345|0123456789012345|0123456789012345|012345678912345
// email=AAAAAAAAAA|adminPPPPPPPPPPP|AAA&uid=10&role=|userPPPPPPPPPPP
// ^^^^^^^^^^|^^^^^^^^^^^^^^^^|^^^
// input
let input = "AAAAAAAAAAadmin\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0bAAA";
let mut ciphertext = encryption_oracle(&key, input);
// substitute the block with admin text in it to make an admin profile!
let admin_block = &ciphertext[1*blocksize..2*blocksize].to_vec();
&mut ciphertext[3*blocksize..4*blocksize].copy_from_slice(&admin_block);
let json = decryption_oracle(&key, &ciphertext);
let obj = json.as_object().unwrap();
assert_eq!(obj["role"], "admin".to_json());
}
|
{
let mut obj = BTreeMap::new();
for pair in input.split('&') {
let mut items = pair.split('=');
match (items.next(), items.next(), items.next()) {
(Some(key), Some(val), None) => {
obj.insert(key.to_string(), Json::String(val.to_string()));
},
_ => {
return Err(());
}
};
}
Ok(Json::Object(obj))
}
|
identifier_body
|
tokenizer.rs
|
/*
* Copyright 2006 Kenta Cho. Some rights reserved.
*/
use std::io::prelude::*;
use std::fs::File;
fn readFile(fileName : &string, separator : &string) -> string {
let mut file = File::open(fileName.unwrap());
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let mut result : Vec[String];
// Returns amount of bytes read and append the result to the buffer
let result = file.read_to_end(&mut contents).unwrap();
for line in result.lines() {
for s in line.split(separator) {
result.push(s.trim());
}
}
result
}
fn
|
() {
}
/*
/*
* Tokenizer.
*/
public class Tokenizer {
private:
public static string[] readFile(string fileName, string separator) {
string[] result;
auto file = new File(fileName, FileMode.In);
char[][] lines = splitLines(file);
foreach(line; lines) {
char[][] spl = split(line, separator);
foreach (char[] s; spl) {
char[] r = trim(s);
if (r.length > 0)
result ~= r.idup;
}
}
return result;
}
}
/*
* CSV format tokenizer.
*/
public class CSVTokenizer {
private:
public static char[][] readFile(string fileName) {
return Tokenizer.readFile(fileName, ",");
}
}
*/
|
main
|
identifier_name
|
tokenizer.rs
|
/*
* Copyright 2006 Kenta Cho. Some rights reserved.
*/
use std::io::prelude::*;
use std::fs::File;
|
file.read_to_string(&mut contents).unwrap();
let mut result : Vec[String];
// Returns amount of bytes read and append the result to the buffer
let result = file.read_to_end(&mut contents).unwrap();
for line in result.lines() {
for s in line.split(separator) {
result.push(s.trim());
}
}
result
}
fn main() {
}
/*
/*
* Tokenizer.
*/
public class Tokenizer {
private:
public static string[] readFile(string fileName, string separator) {
string[] result;
auto file = new File(fileName, FileMode.In);
char[][] lines = splitLines(file);
foreach(line; lines) {
char[][] spl = split(line, separator);
foreach (char[] s; spl) {
char[] r = trim(s);
if (r.length > 0)
result ~= r.idup;
}
}
return result;
}
}
/*
* CSV format tokenizer.
*/
public class CSVTokenizer {
private:
public static char[][] readFile(string fileName) {
return Tokenizer.readFile(fileName, ",");
}
}
*/
|
fn readFile(fileName : &string, separator : &string) -> string {
let mut file = File::open(fileName.unwrap());
let mut contents = String::new();
|
random_line_split
|
tokenizer.rs
|
/*
* Copyright 2006 Kenta Cho. Some rights reserved.
*/
use std::io::prelude::*;
use std::fs::File;
fn readFile(fileName : &string, separator : &string) -> string
|
fn main() {
}
/*
/*
* Tokenizer.
*/
public class Tokenizer {
private:
public static string[] readFile(string fileName, string separator) {
string[] result;
auto file = new File(fileName, FileMode.In);
char[][] lines = splitLines(file);
foreach(line; lines) {
char[][] spl = split(line, separator);
foreach (char[] s; spl) {
char[] r = trim(s);
if (r.length > 0)
result ~= r.idup;
}
}
return result;
}
}
/*
* CSV format tokenizer.
*/
public class CSVTokenizer {
private:
public static char[][] readFile(string fileName) {
return Tokenizer.readFile(fileName, ",");
}
}
*/
|
{
let mut file = File::open(fileName.unwrap());
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let mut result : Vec[String];
// Returns amount of bytes read and append the result to the buffer
let result = file.read_to_end(&mut contents).unwrap();
for line in result.lines() {
for s in line.split(separator) {
result.push(s.trim());
}
}
result
}
|
identifier_body
|
connection.rs
|
// CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use ClientId;
use Result;
use ServerId;
use backoff::Backoff;
use capnp::message::{Builder, HeapAllocator, Reader, ReaderOptions};
use capnp_nonblock::{MessageStream, Segments};
use messages;
use mio::{EventLoop, EventSet, PollOpt, Token};
use mio::Timeout as TimeoutHandle;
use mio::tcp::TcpStream;
use persistent_log::Log;
use server::{Server, ServerTimeout};
use state_machine::StateMachine;
use std::fmt;
use std::net::SocketAddr;
use std::rc::Rc;
fn poll_opt() -> PollOpt {
PollOpt::edge() | PollOpt::oneshot()
}
/// The type of a connection.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum ConnectionKind {
/// A peer in the cluster.
Peer(ServerId),
/// A client which is asking the Raft cluster to do things.
Client(ClientId),
/// Something else.
Unknown,
}
impl ConnectionKind {
/// Returns if the `Connection` is a peer type.
fn is_peer(&self) -> bool {
match *self {
ConnectionKind::Peer(..) => true,
_ => false,
}
}
}
pub struct Connection {
kind: ConnectionKind,
/// The address to reconnect to - for a connection initiated by the remote,
/// this is not the remote address.
addr: SocketAddr,
stream: Option<MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>>>,
backoff: Backoff,
}
impl Connection {
/// Creates a new `Connection` wrapping the provided socket stream.
///
/// The socket must already be connected.
///
/// Note: the caller must manually set the token field after inserting the
/// connection into a slab.
pub fn unknown(socket: TcpStream) -> Result<Connection>
|
/// Creates a new peer connection.
pub fn peer(id: ServerId, addr: SocketAddr) -> Result<Connection> {
let stream = try!(TcpStream::connect(&addr));
Ok(Connection {
kind: ConnectionKind::Peer(id),
addr: addr,
stream: Some(MessageStream::new(stream, ReaderOptions::new())),
backoff: Backoff::with_duration_range(50, 10000),
})
}
pub fn kind(&self) -> &ConnectionKind {
&self.kind
}
pub fn set_kind(&mut self, kind: ConnectionKind) {
self.kind = kind;
}
pub fn addr(&self) -> &SocketAddr {
&self.addr
}
pub fn set_addr(&mut self, addr: SocketAddr) {
self.addr = addr;
}
/// Returns the connection's stream.
/// Must only be called while the connection is active.
fn stream(&self) -> &MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>> {
match self.stream {
Some(ref stream) => stream,
None => panic!(format!("{:?}: not connected", self)),
}
}
/// Returns the connection's mutable stream.
/// Must only be called while the connection is active.
fn stream_mut(&mut self) -> &mut MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>> {
match self.stream {
Some(ref mut stream) => stream,
None => panic!(format!("{:?}: not connected", self)),
}
}
/// Writes queued messages to the socket.
pub fn writable(&mut self) -> Result<()> {
scoped_trace!("{:?}: writable", self);
if let Connection {
stream: Some(ref mut stream),
ref mut backoff,
..
} = *self
{
try!(stream.write());
backoff.reset();
Ok(())
} else {
panic!("{:?}: writable event while not connected", self);
}
}
/// Reads a message from the connection's stream, or if a full message is
/// not available, returns `None`.
///
/// Connections are edge-triggered, so the handler must continue calling
/// until no more messages are returned.
pub fn readable(&mut self) -> Result<Option<Reader<Segments>>> {
scoped_trace!("{:?}: readable", self);
self.stream_mut().read_message().map_err(From::from)
}
/// Queues a message to send to the connection. Returns `true` if the connection should be
/// reregistered with the event loop.
pub fn send_message(&mut self, message: Rc<Builder<HeapAllocator>>) -> Result<bool> {
scoped_trace!("{:?}: send_message", self);
match self.stream {
Some(ref mut stream) => {
// Reregister if the connection is not already registered, and
// there are still messages left to send. MessageStream
// optimistically sends messages, so it's likely that small
// messages can be sent without ever registering.
let unregistered = stream.outbound_queue_len() == 0;
try!(stream.write_message(message));
Ok(unregistered && stream.outbound_queue_len() > 0)
}
None => Ok(false),
}
}
fn events(&self) -> EventSet {
let mut events = EventSet::all();
if self.stream().outbound_queue_len() == 0 {
events = events - EventSet::writable();
}
events
}
/// Registers the connection with the event loop.
pub fn register<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<()>
where
L: Log,
M: StateMachine,
{
scoped_trace!("{:?}: register", self);
event_loop.register(self.stream().inner(), token, self.events(), poll_opt()).map_err(|error| {
scoped_warn!("{:?}: reregister failed: {}", self, error);
From::from(error)
})
}
/// Reregisters the connection with the event loop.
pub fn reregister<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<()>
where
L: Log,
M: StateMachine,
{
scoped_trace!("{:?}: reregister", self);
event_loop.reregister(self.stream().inner(), token, self.events(), poll_opt()).map_err(|error| {
scoped_warn!("{:?}: register failed: {}", self, error);
From::from(error)
})
}
/// Reconnects to the given peer ID and sends the preamble, advertising the
/// given local address to the peer.
pub fn reconnect_peer(&mut self, id: ServerId, local_addr: &SocketAddr) -> Result<()> {
scoped_assert!(self.kind.is_peer());
scoped_trace!("{:?}: reconnect", self);
self.stream = Some(MessageStream::new(try!(TcpStream::connect(&self.addr)), ReaderOptions::new()));
try!(self.send_message(messages::server_connection_preamble(id, local_addr)));
Ok(())
}
/// Resets a peer connection.
pub fn reset_peer<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<(ServerTimeout, TimeoutHandle)>
where
L: Log,
M: StateMachine,
{
scoped_assert!(self.kind.is_peer());
self.stream = None;
let duration = self.backoff.next_backoff_ms();
let timeout = ServerTimeout::Reconnect(token);
let handle = event_loop.timeout_ms(timeout, duration).unwrap();
scoped_info!("{:?}: reset, will attempt to reconnect in {}ms", self, duration);
Ok((timeout, handle))
}
pub fn clear_messages(&mut self) {
if let Some(ref mut stream) = self.stream {
stream.clear_outbound_queue();
}
}
}
impl fmt::Debug for Connection {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
ConnectionKind::Peer(id) => write!(fmt, "PeerConnection({})", id),
ConnectionKind::Client(id) => write!(fmt, "ClientConnection({})", id),
ConnectionKind::Unknown => write!(fmt, "UnknownConnection({})", &self.addr),
}
}
}
|
{
let addr = try!(socket.peer_addr());
Ok(Connection {
kind: ConnectionKind::Unknown,
addr: addr,
stream: Some(MessageStream::new(socket, ReaderOptions::new())),
backoff: Backoff::with_duration_range(50, 10000),
})
}
|
identifier_body
|
connection.rs
|
// CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use ClientId;
use Result;
use ServerId;
use backoff::Backoff;
use capnp::message::{Builder, HeapAllocator, Reader, ReaderOptions};
use capnp_nonblock::{MessageStream, Segments};
use messages;
use mio::{EventLoop, EventSet, PollOpt, Token};
use mio::Timeout as TimeoutHandle;
use mio::tcp::TcpStream;
use persistent_log::Log;
use server::{Server, ServerTimeout};
|
use std::rc::Rc;
fn poll_opt() -> PollOpt {
PollOpt::edge() | PollOpt::oneshot()
}
/// The type of a connection.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum ConnectionKind {
/// A peer in the cluster.
Peer(ServerId),
/// A client which is asking the Raft cluster to do things.
Client(ClientId),
/// Something else.
Unknown,
}
impl ConnectionKind {
/// Returns if the `Connection` is a peer type.
fn is_peer(&self) -> bool {
match *self {
ConnectionKind::Peer(..) => true,
_ => false,
}
}
}
pub struct Connection {
kind: ConnectionKind,
/// The address to reconnect to - for a connection initiated by the remote,
/// this is not the remote address.
addr: SocketAddr,
stream: Option<MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>>>,
backoff: Backoff,
}
impl Connection {
/// Creates a new `Connection` wrapping the provided socket stream.
///
/// The socket must already be connected.
///
/// Note: the caller must manually set the token field after inserting the
/// connection into a slab.
pub fn unknown(socket: TcpStream) -> Result<Connection> {
let addr = try!(socket.peer_addr());
Ok(Connection {
kind: ConnectionKind::Unknown,
addr: addr,
stream: Some(MessageStream::new(socket, ReaderOptions::new())),
backoff: Backoff::with_duration_range(50, 10000),
})
}
/// Creates a new peer connection.
pub fn peer(id: ServerId, addr: SocketAddr) -> Result<Connection> {
let stream = try!(TcpStream::connect(&addr));
Ok(Connection {
kind: ConnectionKind::Peer(id),
addr: addr,
stream: Some(MessageStream::new(stream, ReaderOptions::new())),
backoff: Backoff::with_duration_range(50, 10000),
})
}
pub fn kind(&self) -> &ConnectionKind {
&self.kind
}
pub fn set_kind(&mut self, kind: ConnectionKind) {
self.kind = kind;
}
pub fn addr(&self) -> &SocketAddr {
&self.addr
}
pub fn set_addr(&mut self, addr: SocketAddr) {
self.addr = addr;
}
/// Returns the connection's stream.
/// Must only be called while the connection is active.
fn stream(&self) -> &MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>> {
match self.stream {
Some(ref stream) => stream,
None => panic!(format!("{:?}: not connected", self)),
}
}
/// Returns the connection's mutable stream.
/// Must only be called while the connection is active.
fn stream_mut(&mut self) -> &mut MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>> {
match self.stream {
Some(ref mut stream) => stream,
None => panic!(format!("{:?}: not connected", self)),
}
}
/// Writes queued messages to the socket.
pub fn writable(&mut self) -> Result<()> {
scoped_trace!("{:?}: writable", self);
if let Connection {
stream: Some(ref mut stream),
ref mut backoff,
..
} = *self
{
try!(stream.write());
backoff.reset();
Ok(())
} else {
panic!("{:?}: writable event while not connected", self);
}
}
/// Reads a message from the connection's stream, or if a full message is
/// not available, returns `None`.
///
/// Connections are edge-triggered, so the handler must continue calling
/// until no more messages are returned.
pub fn readable(&mut self) -> Result<Option<Reader<Segments>>> {
scoped_trace!("{:?}: readable", self);
self.stream_mut().read_message().map_err(From::from)
}
/// Queues a message to send to the connection. Returns `true` if the connection should be
/// reregistered with the event loop.
pub fn send_message(&mut self, message: Rc<Builder<HeapAllocator>>) -> Result<bool> {
scoped_trace!("{:?}: send_message", self);
match self.stream {
Some(ref mut stream) => {
// Reregister if the connection is not already registered, and
// there are still messages left to send. MessageStream
// optimistically sends messages, so it's likely that small
// messages can be sent without ever registering.
let unregistered = stream.outbound_queue_len() == 0;
try!(stream.write_message(message));
Ok(unregistered && stream.outbound_queue_len() > 0)
}
None => Ok(false),
}
}
fn events(&self) -> EventSet {
let mut events = EventSet::all();
if self.stream().outbound_queue_len() == 0 {
events = events - EventSet::writable();
}
events
}
/// Registers the connection with the event loop.
pub fn register<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<()>
where
L: Log,
M: StateMachine,
{
scoped_trace!("{:?}: register", self);
event_loop.register(self.stream().inner(), token, self.events(), poll_opt()).map_err(|error| {
scoped_warn!("{:?}: reregister failed: {}", self, error);
From::from(error)
})
}
/// Reregisters the connection with the event loop.
pub fn reregister<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<()>
where
L: Log,
M: StateMachine,
{
scoped_trace!("{:?}: reregister", self);
event_loop.reregister(self.stream().inner(), token, self.events(), poll_opt()).map_err(|error| {
scoped_warn!("{:?}: register failed: {}", self, error);
From::from(error)
})
}
/// Reconnects to the given peer ID and sends the preamble, advertising the
/// given local address to the peer.
pub fn reconnect_peer(&mut self, id: ServerId, local_addr: &SocketAddr) -> Result<()> {
scoped_assert!(self.kind.is_peer());
scoped_trace!("{:?}: reconnect", self);
self.stream = Some(MessageStream::new(try!(TcpStream::connect(&self.addr)), ReaderOptions::new()));
try!(self.send_message(messages::server_connection_preamble(id, local_addr)));
Ok(())
}
/// Resets a peer connection.
pub fn reset_peer<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<(ServerTimeout, TimeoutHandle)>
where
L: Log,
M: StateMachine,
{
scoped_assert!(self.kind.is_peer());
self.stream = None;
let duration = self.backoff.next_backoff_ms();
let timeout = ServerTimeout::Reconnect(token);
let handle = event_loop.timeout_ms(timeout, duration).unwrap();
scoped_info!("{:?}: reset, will attempt to reconnect in {}ms", self, duration);
Ok((timeout, handle))
}
pub fn clear_messages(&mut self) {
if let Some(ref mut stream) = self.stream {
stream.clear_outbound_queue();
}
}
}
impl fmt::Debug for Connection {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
ConnectionKind::Peer(id) => write!(fmt, "PeerConnection({})", id),
ConnectionKind::Client(id) => write!(fmt, "ClientConnection({})", id),
ConnectionKind::Unknown => write!(fmt, "UnknownConnection({})", &self.addr),
}
}
}
|
use state_machine::StateMachine;
use std::fmt;
use std::net::SocketAddr;
|
random_line_split
|
connection.rs
|
// CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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.
// This program is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use ClientId;
use Result;
use ServerId;
use backoff::Backoff;
use capnp::message::{Builder, HeapAllocator, Reader, ReaderOptions};
use capnp_nonblock::{MessageStream, Segments};
use messages;
use mio::{EventLoop, EventSet, PollOpt, Token};
use mio::Timeout as TimeoutHandle;
use mio::tcp::TcpStream;
use persistent_log::Log;
use server::{Server, ServerTimeout};
use state_machine::StateMachine;
use std::fmt;
use std::net::SocketAddr;
use std::rc::Rc;
fn poll_opt() -> PollOpt {
PollOpt::edge() | PollOpt::oneshot()
}
/// The type of a connection.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum ConnectionKind {
/// A peer in the cluster.
Peer(ServerId),
/// A client which is asking the Raft cluster to do things.
Client(ClientId),
/// Something else.
Unknown,
}
impl ConnectionKind {
/// Returns if the `Connection` is a peer type.
fn is_peer(&self) -> bool {
match *self {
ConnectionKind::Peer(..) => true,
_ => false,
}
}
}
pub struct Connection {
kind: ConnectionKind,
/// The address to reconnect to - for a connection initiated by the remote,
/// this is not the remote address.
addr: SocketAddr,
stream: Option<MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>>>,
backoff: Backoff,
}
impl Connection {
/// Creates a new `Connection` wrapping the provided socket stream.
///
/// The socket must already be connected.
///
/// Note: the caller must manually set the token field after inserting the
/// connection into a slab.
pub fn unknown(socket: TcpStream) -> Result<Connection> {
let addr = try!(socket.peer_addr());
Ok(Connection {
kind: ConnectionKind::Unknown,
addr: addr,
stream: Some(MessageStream::new(socket, ReaderOptions::new())),
backoff: Backoff::with_duration_range(50, 10000),
})
}
/// Creates a new peer connection.
pub fn peer(id: ServerId, addr: SocketAddr) -> Result<Connection> {
let stream = try!(TcpStream::connect(&addr));
Ok(Connection {
kind: ConnectionKind::Peer(id),
addr: addr,
stream: Some(MessageStream::new(stream, ReaderOptions::new())),
backoff: Backoff::with_duration_range(50, 10000),
})
}
pub fn kind(&self) -> &ConnectionKind {
&self.kind
}
pub fn set_kind(&mut self, kind: ConnectionKind) {
self.kind = kind;
}
pub fn
|
(&self) -> &SocketAddr {
&self.addr
}
pub fn set_addr(&mut self, addr: SocketAddr) {
self.addr = addr;
}
/// Returns the connection's stream.
/// Must only be called while the connection is active.
fn stream(&self) -> &MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>> {
match self.stream {
Some(ref stream) => stream,
None => panic!(format!("{:?}: not connected", self)),
}
}
/// Returns the connection's mutable stream.
/// Must only be called while the connection is active.
fn stream_mut(&mut self) -> &mut MessageStream<TcpStream, HeapAllocator, Rc<Builder<HeapAllocator>>> {
match self.stream {
Some(ref mut stream) => stream,
None => panic!(format!("{:?}: not connected", self)),
}
}
/// Writes queued messages to the socket.
pub fn writable(&mut self) -> Result<()> {
scoped_trace!("{:?}: writable", self);
if let Connection {
stream: Some(ref mut stream),
ref mut backoff,
..
} = *self
{
try!(stream.write());
backoff.reset();
Ok(())
} else {
panic!("{:?}: writable event while not connected", self);
}
}
/// Reads a message from the connection's stream, or if a full message is
/// not available, returns `None`.
///
/// Connections are edge-triggered, so the handler must continue calling
/// until no more messages are returned.
pub fn readable(&mut self) -> Result<Option<Reader<Segments>>> {
scoped_trace!("{:?}: readable", self);
self.stream_mut().read_message().map_err(From::from)
}
/// Queues a message to send to the connection. Returns `true` if the connection should be
/// reregistered with the event loop.
pub fn send_message(&mut self, message: Rc<Builder<HeapAllocator>>) -> Result<bool> {
scoped_trace!("{:?}: send_message", self);
match self.stream {
Some(ref mut stream) => {
// Reregister if the connection is not already registered, and
// there are still messages left to send. MessageStream
// optimistically sends messages, so it's likely that small
// messages can be sent without ever registering.
let unregistered = stream.outbound_queue_len() == 0;
try!(stream.write_message(message));
Ok(unregistered && stream.outbound_queue_len() > 0)
}
None => Ok(false),
}
}
fn events(&self) -> EventSet {
let mut events = EventSet::all();
if self.stream().outbound_queue_len() == 0 {
events = events - EventSet::writable();
}
events
}
/// Registers the connection with the event loop.
pub fn register<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<()>
where
L: Log,
M: StateMachine,
{
scoped_trace!("{:?}: register", self);
event_loop.register(self.stream().inner(), token, self.events(), poll_opt()).map_err(|error| {
scoped_warn!("{:?}: reregister failed: {}", self, error);
From::from(error)
})
}
/// Reregisters the connection with the event loop.
pub fn reregister<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<()>
where
L: Log,
M: StateMachine,
{
scoped_trace!("{:?}: reregister", self);
event_loop.reregister(self.stream().inner(), token, self.events(), poll_opt()).map_err(|error| {
scoped_warn!("{:?}: register failed: {}", self, error);
From::from(error)
})
}
/// Reconnects to the given peer ID and sends the preamble, advertising the
/// given local address to the peer.
pub fn reconnect_peer(&mut self, id: ServerId, local_addr: &SocketAddr) -> Result<()> {
scoped_assert!(self.kind.is_peer());
scoped_trace!("{:?}: reconnect", self);
self.stream = Some(MessageStream::new(try!(TcpStream::connect(&self.addr)), ReaderOptions::new()));
try!(self.send_message(messages::server_connection_preamble(id, local_addr)));
Ok(())
}
/// Resets a peer connection.
pub fn reset_peer<L, M>(&mut self, event_loop: &mut EventLoop<Server<L, M>>, token: Token) -> Result<(ServerTimeout, TimeoutHandle)>
where
L: Log,
M: StateMachine,
{
scoped_assert!(self.kind.is_peer());
self.stream = None;
let duration = self.backoff.next_backoff_ms();
let timeout = ServerTimeout::Reconnect(token);
let handle = event_loop.timeout_ms(timeout, duration).unwrap();
scoped_info!("{:?}: reset, will attempt to reconnect in {}ms", self, duration);
Ok((timeout, handle))
}
pub fn clear_messages(&mut self) {
if let Some(ref mut stream) = self.stream {
stream.clear_outbound_queue();
}
}
}
impl fmt::Debug for Connection {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
ConnectionKind::Peer(id) => write!(fmt, "PeerConnection({})", id),
ConnectionKind::Client(id) => write!(fmt, "ClientConnection({})", id),
ConnectionKind::Unknown => write!(fmt, "UnknownConnection({})", &self.addr),
}
}
}
|
addr
|
identifier_name
|
mod.rs
|
use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
TextAscii,
TextUtf8,
Binary,
Float,
Date,
}
// Element DOM
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub enum ElementContent {
Master(Vec<Rc<Element>>),
Unsigned(u64),
Signed(i64),
Binary(Rc<Vec<u8>>),
Text(Rc<String>),
Float(f64),
MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC
Unknown(u64, Rc<Vec<u8>>)
}
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub struct Element {
pub class : database::Class,
pub content : ElementContent,
}
// Cosy constructors
pub fn el_bin (c: database::Class, d:Vec<u8>) -> Element { Element { class: c, content: ElementContent::Binary (Rc::new( d )) }}
pub fn el_uns (c: database::Class, d:u64 ) -> Element { Element { class: c, content: ElementContent::Unsigned( d ) }}
pub fn el_sig (c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::Signed ( d ) }}
pub fn el_flo (c: database::Class, d:f64 ) -> Element { Element { class: c, content: ElementContent::Float ( d ) }}
pub fn el_txt (c: database::Class, d:String ) -> Element { Element { class: c, content: ElementContent::Text (Rc::new( d )) }}
pub fn
|
(c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::MatroskaDate(d)}}
pub fn el<T>(c: database::Class, d:T) -> Element where T:IntoIterator<Item=Element> {
let mut v = vec![];
for i in d {
v.push ( Rc::new(i) );
}
Element { class: c, content: ElementContent::Master (v) }
}
pub fn typical_matroska_header(webm : bool) -> Element {
use self::database::Class::*;
use self::ElementContent::{Unsigned,Text,Master};
let doctype = if webm { "webm" } else { "matroska"}.to_string();
Element { class: EBML, content: Master(vec![
Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLReadVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLMaxIDLength, content: Unsigned(4)}),
Rc::new(Element {class: EBMLMaxSizeLength, content: Unsigned(8)}),
Rc::new(Element {class: DocType, content: Text(Rc::new(doctype))}),
Rc::new(Element {class: DocTypeVersion, content: Unsigned(2)}),
Rc::new(Element {class: DocTypeReadVersion,content: Unsigned(2)}),
])}
}
|
el_date
|
identifier_name
|
mod.rs
|
use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
TextAscii,
TextUtf8,
Binary,
Float,
Date,
}
// Element DOM
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub enum ElementContent {
Master(Vec<Rc<Element>>),
Unsigned(u64),
Signed(i64),
Binary(Rc<Vec<u8>>),
Text(Rc<String>),
Float(f64),
MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC
Unknown(u64, Rc<Vec<u8>>)
}
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub struct Element {
pub class : database::Class,
pub content : ElementContent,
}
// Cosy constructors
pub fn el_bin (c: database::Class, d:Vec<u8>) -> Element { Element { class: c, content: ElementContent::Binary (Rc::new( d )) }}
pub fn el_uns (c: database::Class, d:u64 ) -> Element { Element { class: c, content: ElementContent::Unsigned( d ) }}
pub fn el_sig (c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::Signed ( d ) }}
pub fn el_flo (c: database::Class, d:f64 ) -> Element { Element { class: c, content: ElementContent::Float ( d ) }}
pub fn el_txt (c: database::Class, d:String ) -> Element { Element { class: c, content: ElementContent::Text (Rc::new( d )) }}
pub fn el_date(c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::MatroskaDate(d)}}
pub fn el<T>(c: database::Class, d:T) -> Element where T:IntoIterator<Item=Element> {
let mut v = vec![];
for i in d {
v.push ( Rc::new(i) );
}
Element { class: c, content: ElementContent::Master (v) }
}
pub fn typical_matroska_header(webm : bool) -> Element {
use self::database::Class::*;
use self::ElementContent::{Unsigned,Text,Master};
let doctype = if webm { "webm" } else
|
.to_string();
Element { class: EBML, content: Master(vec![
Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLReadVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLMaxIDLength, content: Unsigned(4)}),
Rc::new(Element {class: EBMLMaxSizeLength, content: Unsigned(8)}),
Rc::new(Element {class: DocType, content: Text(Rc::new(doctype))}),
Rc::new(Element {class: DocTypeVersion, content: Unsigned(2)}),
Rc::new(Element {class: DocTypeReadVersion,content: Unsigned(2)}),
])}
}
|
{ "matroska"}
|
conditional_block
|
mod.rs
|
use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
TextAscii,
TextUtf8,
Binary,
Float,
Date,
}
// Element DOM
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub enum ElementContent {
Master(Vec<Rc<Element>>),
Unsigned(u64),
Signed(i64),
Binary(Rc<Vec<u8>>),
Text(Rc<String>),
Float(f64),
MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC
Unknown(u64, Rc<Vec<u8>>)
}
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub struct Element {
pub class : database::Class,
pub content : ElementContent,
}
// Cosy constructors
pub fn el_bin (c: database::Class, d:Vec<u8>) -> Element { Element { class: c, content: ElementContent::Binary (Rc::new( d )) }}
pub fn el_uns (c: database::Class, d:u64 ) -> Element { Element { class: c, content: ElementContent::Unsigned( d ) }}
pub fn el_sig (c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::Signed ( d ) }}
pub fn el_flo (c: database::Class, d:f64 ) -> Element { Element { class: c, content: ElementContent::Float ( d ) }}
pub fn el_txt (c: database::Class, d:String ) -> Element { Element { class: c, content: ElementContent::Text (Rc::new( d )) }}
pub fn el_date(c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::MatroskaDate(d)}}
pub fn el<T>(c: database::Class, d:T) -> Element where T:IntoIterator<Item=Element> {
let mut v = vec![];
for i in d {
v.push ( Rc::new(i) );
}
Element { class: c, content: ElementContent::Master (v) }
}
pub fn typical_matroska_header(webm : bool) -> Element
|
{
use self::database::Class::*;
use self::ElementContent::{Unsigned,Text,Master};
let doctype = if webm { "webm" } else { "matroska"}.to_string();
Element { class: EBML, content: Master(vec![
Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLReadVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLMaxIDLength, content: Unsigned(4)}),
Rc::new(Element {class: EBMLMaxSizeLength, content: Unsigned(8)}),
Rc::new(Element {class: DocType, content: Text(Rc::new(doctype))}),
Rc::new(Element {class: DocTypeVersion, content: Unsigned(2)}),
Rc::new(Element {class: DocTypeReadVersion,content: Unsigned(2)}),
])}
}
|
identifier_body
|
|
mod.rs
|
use std::rc::Rc;
use std::vec::Vec;
pub mod database;
pub mod parser; // bytes -> events
pub mod builder; // events -> DOM
pub mod generator; // DOM -> bytes
pub mod templates;
pub mod midlevel; // events -> events+DOM
#[derive(Debug,Eq,PartialEq,Clone,Copy)]
pub enum Type {
Master,
Unsigned,
Signed,
TextAscii,
TextUtf8,
Binary,
Float,
Date,
}
// Element DOM
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub enum ElementContent {
Master(Vec<Rc<Element>>),
Unsigned(u64),
Signed(i64),
Binary(Rc<Vec<u8>>),
Text(Rc<String>),
|
}
#[derive(PartialEq,Debug,PartialOrd,Clone)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
pub struct Element {
pub class : database::Class,
pub content : ElementContent,
}
// Cosy constructors
pub fn el_bin (c: database::Class, d:Vec<u8>) -> Element { Element { class: c, content: ElementContent::Binary (Rc::new( d )) }}
pub fn el_uns (c: database::Class, d:u64 ) -> Element { Element { class: c, content: ElementContent::Unsigned( d ) }}
pub fn el_sig (c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::Signed ( d ) }}
pub fn el_flo (c: database::Class, d:f64 ) -> Element { Element { class: c, content: ElementContent::Float ( d ) }}
pub fn el_txt (c: database::Class, d:String ) -> Element { Element { class: c, content: ElementContent::Text (Rc::new( d )) }}
pub fn el_date(c: database::Class, d:i64 ) -> Element { Element { class: c, content: ElementContent::MatroskaDate(d)}}
pub fn el<T>(c: database::Class, d:T) -> Element where T:IntoIterator<Item=Element> {
let mut v = vec![];
for i in d {
v.push ( Rc::new(i) );
}
Element { class: c, content: ElementContent::Master (v) }
}
pub fn typical_matroska_header(webm : bool) -> Element {
use self::database::Class::*;
use self::ElementContent::{Unsigned,Text,Master};
let doctype = if webm { "webm" } else { "matroska"}.to_string();
Element { class: EBML, content: Master(vec![
Rc::new(Element {class: EBMLVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLReadVersion, content: Unsigned(1)}),
Rc::new(Element {class: EBMLMaxIDLength, content: Unsigned(4)}),
Rc::new(Element {class: EBMLMaxSizeLength, content: Unsigned(8)}),
Rc::new(Element {class: DocType, content: Text(Rc::new(doctype))}),
Rc::new(Element {class: DocTypeVersion, content: Unsigned(2)}),
Rc::new(Element {class: DocTypeReadVersion,content: Unsigned(2)}),
])}
}
|
Float(f64),
MatroskaDate(i64), // Nanoseconds since 20010101_000000_UTC
Unknown(u64, Rc<Vec<u8>>)
|
random_line_split
|
membership.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::Result;
use async_trait::async_trait;
use std::panic::RefUnwindSafe;
use std::sync::Arc;
use crate::MononokeIdentitySet;
pub type ArcMembershipChecker = Arc<dyn MembershipChecker + Send + Sync + RefUnwindSafe +'static>;
pub type BoxMembershipChecker = Box<dyn MembershipChecker + Send + Sync + RefUnwindSafe +'static>;
#[async_trait]
pub trait MembershipChecker {
async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool>;
}
pub struct MembershipCheckerBuilder {}
impl MembershipCheckerBuilder {
pub fn always_member() -> BoxMembershipChecker {
Box::new(AlwaysMember {})
}
pub fn never_member() -> BoxMembershipChecker {
Box::new(NeverMember {})
}
pub fn allowlist_checker(allowlist: MononokeIdentitySet) -> BoxMembershipChecker {
Box::new(AllowlistChecker { allowlist })
}
}
struct AlwaysMember {}
#[async_trait]
impl MembershipChecker for AlwaysMember {
async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool> {
Ok(true)
}
}
struct NeverMember {}
#[async_trait]
impl MembershipChecker for NeverMember {
async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool> {
Ok(false)
}
}
|
struct AllowlistChecker {
allowlist: MononokeIdentitySet,
}
#[async_trait]
impl MembershipChecker for AllowlistChecker {
async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool> {
Ok(!self.allowlist.is_disjoint(identities))
}
}
|
random_line_split
|
|
membership.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::Result;
use async_trait::async_trait;
use std::panic::RefUnwindSafe;
use std::sync::Arc;
use crate::MononokeIdentitySet;
pub type ArcMembershipChecker = Arc<dyn MembershipChecker + Send + Sync + RefUnwindSafe +'static>;
pub type BoxMembershipChecker = Box<dyn MembershipChecker + Send + Sync + RefUnwindSafe +'static>;
#[async_trait]
pub trait MembershipChecker {
async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool>;
}
pub struct MembershipCheckerBuilder {}
impl MembershipCheckerBuilder {
pub fn always_member() -> BoxMembershipChecker {
Box::new(AlwaysMember {})
}
pub fn never_member() -> BoxMembershipChecker {
Box::new(NeverMember {})
}
pub fn allowlist_checker(allowlist: MononokeIdentitySet) -> BoxMembershipChecker {
Box::new(AllowlistChecker { allowlist })
}
}
struct AlwaysMember {}
#[async_trait]
impl MembershipChecker for AlwaysMember {
async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool>
|
}
struct NeverMember {}
#[async_trait]
impl MembershipChecker for NeverMember {
async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool> {
Ok(false)
}
}
struct AllowlistChecker {
allowlist: MononokeIdentitySet,
}
#[async_trait]
impl MembershipChecker for AllowlistChecker {
async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool> {
Ok(!self.allowlist.is_disjoint(identities))
}
}
|
{
Ok(true)
}
|
identifier_body
|
membership.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::Result;
use async_trait::async_trait;
use std::panic::RefUnwindSafe;
use std::sync::Arc;
use crate::MononokeIdentitySet;
pub type ArcMembershipChecker = Arc<dyn MembershipChecker + Send + Sync + RefUnwindSafe +'static>;
pub type BoxMembershipChecker = Box<dyn MembershipChecker + Send + Sync + RefUnwindSafe +'static>;
#[async_trait]
pub trait MembershipChecker {
async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool>;
}
pub struct MembershipCheckerBuilder {}
impl MembershipCheckerBuilder {
pub fn
|
() -> BoxMembershipChecker {
Box::new(AlwaysMember {})
}
pub fn never_member() -> BoxMembershipChecker {
Box::new(NeverMember {})
}
pub fn allowlist_checker(allowlist: MononokeIdentitySet) -> BoxMembershipChecker {
Box::new(AllowlistChecker { allowlist })
}
}
struct AlwaysMember {}
#[async_trait]
impl MembershipChecker for AlwaysMember {
async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool> {
Ok(true)
}
}
struct NeverMember {}
#[async_trait]
impl MembershipChecker for NeverMember {
async fn is_member(&self, _identities: &MononokeIdentitySet) -> Result<bool> {
Ok(false)
}
}
struct AllowlistChecker {
allowlist: MononokeIdentitySet,
}
#[async_trait]
impl MembershipChecker for AllowlistChecker {
async fn is_member(&self, identities: &MononokeIdentitySet) -> Result<bool> {
Ok(!self.allowlist.is_disjoint(identities))
}
}
|
always_member
|
identifier_name
|
issue-36023.rs
|
// Copyright 2016 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.
// run-pass
#![allow(unused_variables)]
use std::ops::Deref;
fn main() {
if env_var("FOOBAR").as_ref().map(Deref::deref).ok() == Some("yes") {
panic!()
}
let env_home: Result<String, ()> = Ok("foo-bar-baz".to_string());
let env_home = env_home.as_ref().map(Deref::deref).ok();
if env_home == Some("")
|
}
#[inline(never)]
fn env_var(s: &str) -> Result<String, VarError> {
Err(VarError::NotPresent)
}
pub enum VarError {
NotPresent,
NotUnicode(String),
}
|
{ panic!() }
|
conditional_block
|
issue-36023.rs
|
// Copyright 2016 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.
// run-pass
#![allow(unused_variables)]
use std::ops::Deref;
fn main() {
if env_var("FOOBAR").as_ref().map(Deref::deref).ok() == Some("yes") {
panic!()
}
let env_home: Result<String, ()> = Ok("foo-bar-baz".to_string());
let env_home = env_home.as_ref().map(Deref::deref).ok();
if env_home == Some("") { panic!() }
}
#[inline(never)]
fn
|
(s: &str) -> Result<String, VarError> {
Err(VarError::NotPresent)
}
pub enum VarError {
NotPresent,
NotUnicode(String),
}
|
env_var
|
identifier_name
|
issue-36023.rs
|
// Copyright 2016 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.
|
use std::ops::Deref;
fn main() {
if env_var("FOOBAR").as_ref().map(Deref::deref).ok() == Some("yes") {
panic!()
}
let env_home: Result<String, ()> = Ok("foo-bar-baz".to_string());
let env_home = env_home.as_ref().map(Deref::deref).ok();
if env_home == Some("") { panic!() }
}
#[inline(never)]
fn env_var(s: &str) -> Result<String, VarError> {
Err(VarError::NotPresent)
}
pub enum VarError {
NotPresent,
NotUnicode(String),
}
|
// run-pass
#![allow(unused_variables)]
|
random_line_split
|
main.rs
|
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate mui;
use std::cell::Cell;
use mui::prelude::*;
fn main() {
let mut app = mui::App::new("Mui Widgets Demo!");
// primitives
let rect = mui::Rect::new("r1", true);
rect.set_zpos(3);
app.add_widget(&rect);
let count = Cell::new(0);
let count2 = Cell::new(0);
// sa - stand alone
let mut sa_button = mui::Button::new("b1");
sa_button.set_text("I'm a button");
sa_button.set_xy(700.0, 300.0);
//let cl = sa_button.clone();
sa_button.set_on_click_fn(Box::new(move |this| {
this.set_text("Told you!");
}));
app.add_widget(&sa_button);
let mut button = mui::Button::new("b2");
button.set_text("Click me");
button.set_on_click_fn(Box::new(move |this| {
count.set(count.get()+1);
this.set_text(format!("Clicked {}", count.get()));
}));
let mut button2 = mui::Button::new("b3");
button2.set_text("Click me");
button2.set_on_click_fn(Box::new(move |this| {
count2.set(count2.get()+1);
this.set_text(format!("Clicked {}", count2.get()));
}));
|
layout.set_zpos(5);
layout.add_widget(&button);
layout.add_widget(&button2);
app.add_widget(&layout);
let sa_textbox = mui::TextBox::new("textbox");
sa_textbox.set_xy(600.0, 200.0);
app.add_widget(&sa_textbox);
app.run();
}
|
let mut layout = mui::BoxLayout::new("l1");
layout.set_xy(300.0, 40.0);
|
random_line_split
|
main.rs
|
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate mui;
use std::cell::Cell;
use mui::prelude::*;
fn
|
() {
let mut app = mui::App::new("Mui Widgets Demo!");
// primitives
let rect = mui::Rect::new("r1", true);
rect.set_zpos(3);
app.add_widget(&rect);
let count = Cell::new(0);
let count2 = Cell::new(0);
// sa - stand alone
let mut sa_button = mui::Button::new("b1");
sa_button.set_text("I'm a button");
sa_button.set_xy(700.0, 300.0);
//let cl = sa_button.clone();
sa_button.set_on_click_fn(Box::new(move |this| {
this.set_text("Told you!");
}));
app.add_widget(&sa_button);
let mut button = mui::Button::new("b2");
button.set_text("Click me");
button.set_on_click_fn(Box::new(move |this| {
count.set(count.get()+1);
this.set_text(format!("Clicked {}", count.get()));
}));
let mut button2 = mui::Button::new("b3");
button2.set_text("Click me");
button2.set_on_click_fn(Box::new(move |this| {
count2.set(count2.get()+1);
this.set_text(format!("Clicked {}", count2.get()));
}));
let mut layout = mui::BoxLayout::new("l1");
layout.set_xy(300.0, 40.0);
layout.set_zpos(5);
layout.add_widget(&button);
layout.add_widget(&button2);
app.add_widget(&layout);
let sa_textbox = mui::TextBox::new("textbox");
sa_textbox.set_xy(600.0, 200.0);
app.add_widget(&sa_textbox);
app.run();
}
|
main
|
identifier_name
|
main.rs
|
#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
extern crate mui;
use std::cell::Cell;
use mui::prelude::*;
fn main()
|
let mut button = mui::Button::new("b2");
button.set_text("Click me");
button.set_on_click_fn(Box::new(move |this| {
count.set(count.get()+1);
this.set_text(format!("Clicked {}", count.get()));
}));
let mut button2 = mui::Button::new("b3");
button2.set_text("Click me");
button2.set_on_click_fn(Box::new(move |this| {
count2.set(count2.get()+1);
this.set_text(format!("Clicked {}", count2.get()));
}));
let mut layout = mui::BoxLayout::new("l1");
layout.set_xy(300.0, 40.0);
layout.set_zpos(5);
layout.add_widget(&button);
layout.add_widget(&button2);
app.add_widget(&layout);
let sa_textbox = mui::TextBox::new("textbox");
sa_textbox.set_xy(600.0, 200.0);
app.add_widget(&sa_textbox);
app.run();
}
|
{
let mut app = mui::App::new("Mui Widgets Demo!");
// primitives
let rect = mui::Rect::new("r1", true);
rect.set_zpos(3);
app.add_widget(&rect);
let count = Cell::new(0);
let count2 = Cell::new(0);
// sa - stand alone
let mut sa_button = mui::Button::new("b1");
sa_button.set_text("I'm a button");
sa_button.set_xy(700.0, 300.0);
//let cl = sa_button.clone();
sa_button.set_on_click_fn(Box::new(move |this| {
this.set_text("Told you!");
}));
app.add_widget(&sa_button);
|
identifier_body
|
issue-15094.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
use std::{fmt, ops};
struct Shower<T> {
x: T
}
impl<T: fmt::Show> ops::Fn<(), ()> for Shower<T> {
fn
|
(&self, _args: ()) {
//~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn
println!("{}", self.x);
}
}
fn make_shower<T>(x: T) -> Shower<T> {
Shower { x: x }
}
pub fn main() {
let show3 = make_shower(3i);
show3();
}
|
call
|
identifier_name
|
issue-15094.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
use std::{fmt, ops};
struct Shower<T> {
x: T
}
impl<T: fmt::Show> ops::Fn<(), ()> for Shower<T> {
fn call(&self, _args: ()) {
//~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn
println!("{}", self.x);
}
}
fn make_shower<T>(x: T) -> Shower<T> {
Shower { x: x }
}
pub fn main()
|
{
let show3 = make_shower(3i);
show3();
}
|
identifier_body
|
|
issue-15094.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.
|
// except according to those terms.
#![feature(unboxed_closures)]
use std::{fmt, ops};
struct Shower<T> {
x: T
}
impl<T: fmt::Show> ops::Fn<(), ()> for Shower<T> {
fn call(&self, _args: ()) {
//~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn
println!("{}", self.x);
}
}
fn make_shower<T>(x: T) -> Shower<T> {
Shower { x: x }
}
pub fn main() {
let show3 = make_shower(3i);
show3();
}
|
//
// 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
|
random_line_split
|
issue-7663.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs)]
#![deny(unused_imports)]
#![allow(dead_code)]
mod test1 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test1::foo::*; //~ ERROR: unused import
|
pub fn my_main() { assert!(p() == 2); }
}
}
mod test2 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test2::foo::p; //~ ERROR: unused import
use test2::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
mod test3 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test3::foo::*; //~ ERROR: unused import
use test3::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
fn main() {
}
|
use test1::bar::*;
|
random_line_split
|
issue-7663.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs)]
#![deny(unused_imports)]
#![allow(dead_code)]
mod test1 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test1::foo::*; //~ ERROR: unused import
use test1::bar::*;
pub fn my_main() { assert!(p() == 2); }
}
}
mod test2 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test2::foo::p; //~ ERROR: unused import
use test2::bar::p;
pub fn my_main()
|
}
}
mod test3 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test3::foo::*; //~ ERROR: unused import
use test3::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
fn main() {
}
|
{ assert!(p() == 2); }
|
identifier_body
|
issue-7663.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs)]
#![deny(unused_imports)]
#![allow(dead_code)]
mod test1 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test1::foo::*; //~ ERROR: unused import
use test1::bar::*;
pub fn my_main() { assert!(p() == 2); }
}
}
mod test2 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn
|
() -> int { 2 } }
pub mod baz {
use test2::foo::p; //~ ERROR: unused import
use test2::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
mod test3 {
mod foo { pub fn p() -> int { 1 } }
mod bar { pub fn p() -> int { 2 } }
pub mod baz {
use test3::foo::*; //~ ERROR: unused import
use test3::bar::p;
pub fn my_main() { assert!(p() == 2); }
}
}
fn main() {
}
|
p
|
identifier_name
|
parser_utils.rs
|
use std::collections::LinkedList;
use std::iter::Iterator;
use std::vec::Vec;
use lexer::Token;
use interpreter::ProgramStore;
use interpreter::FunctionInfo;
/// This function filters out comments and doubled newlines
/// It also registers the functions with the program store
pub fn filter_pass(tokens: Vec<Token>, mut program: ProgramStore) -> Result<(Vec<Token>, ProgramStore), String> {
let mut tok_it = tokens.iter().peekable();
let mut output_tokens: Vec<Token> = Vec::new();
while let Some(&token) = tok_it.peek() {
match token {
// Remove doubled newline and comments, such that any sequence
// of newlines and comments gets shrinked to a single newline token
&Token::Newline => {
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
match next_token {
&Token::Newline | &Token::Comment(_) => {
continue;
}
_ => {
output_tokens.push(Token::Newline);
}
}
}
}
// remove comments just by ignoring them
&Token::Comment(_) => {
tok_it.next();
}
// on a define, create the empty FunctionInfo struct and put it into ProgramStore
&Token::Define => {
output_tokens.push(Token::Define);
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
if let &Token::Identifier(ref name) = next_token {
|
} else {
return Err(format!("expected function name but found {:?}", next_token));
}
}
}
// simply copy all other tokens
_ => {
output_tokens.push(token.clone());
tok_it.next();
}
}
}
Ok((output_tokens, program))
}
pub fn blockify_pass(tokens: Vec<Token>) -> Result<LinkedList<Vec<Token>>, String> {
let mut tok_it = tokens.into_iter();
let mut block = Vec::new();
let mut block_list = LinkedList::new();
while let Some(token) = tok_it.next() {
match token {
Token::Define => {
if block.len()!= 0 && block[0] == Token::Define {
block_list.push_back(block);
}
block = Vec::new();
}
_ => {}
}
block.push(token);
}
// Add last block to block list
block_list.push_back(block);
Ok(block_list)
}
|
program = try!(program.add_function(name.clone(), FunctionInfo::named_new(name)));
|
random_line_split
|
parser_utils.rs
|
use std::collections::LinkedList;
use std::iter::Iterator;
use std::vec::Vec;
use lexer::Token;
use interpreter::ProgramStore;
use interpreter::FunctionInfo;
/// This function filters out comments and doubled newlines
/// It also registers the functions with the program store
pub fn filter_pass(tokens: Vec<Token>, mut program: ProgramStore) -> Result<(Vec<Token>, ProgramStore), String> {
let mut tok_it = tokens.iter().peekable();
let mut output_tokens: Vec<Token> = Vec::new();
while let Some(&token) = tok_it.peek() {
match token {
// Remove doubled newline and comments, such that any sequence
// of newlines and comments gets shrinked to a single newline token
&Token::Newline => {
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
match next_token {
&Token::Newline | &Token::Comment(_) => {
continue;
}
_ => {
output_tokens.push(Token::Newline);
}
}
}
}
// remove comments just by ignoring them
&Token::Comment(_) => {
tok_it.next();
}
// on a define, create the empty FunctionInfo struct and put it into ProgramStore
&Token::Define => {
output_tokens.push(Token::Define);
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
if let &Token::Identifier(ref name) = next_token {
program = try!(program.add_function(name.clone(), FunctionInfo::named_new(name)));
} else {
return Err(format!("expected function name but found {:?}", next_token));
}
}
}
// simply copy all other tokens
_ => {
output_tokens.push(token.clone());
tok_it.next();
}
}
}
Ok((output_tokens, program))
}
pub fn
|
(tokens: Vec<Token>) -> Result<LinkedList<Vec<Token>>, String> {
let mut tok_it = tokens.into_iter();
let mut block = Vec::new();
let mut block_list = LinkedList::new();
while let Some(token) = tok_it.next() {
match token {
Token::Define => {
if block.len()!= 0 && block[0] == Token::Define {
block_list.push_back(block);
}
block = Vec::new();
}
_ => {}
}
block.push(token);
}
// Add last block to block list
block_list.push_back(block);
Ok(block_list)
}
|
blockify_pass
|
identifier_name
|
parser_utils.rs
|
use std::collections::LinkedList;
use std::iter::Iterator;
use std::vec::Vec;
use lexer::Token;
use interpreter::ProgramStore;
use interpreter::FunctionInfo;
/// This function filters out comments and doubled newlines
/// It also registers the functions with the program store
pub fn filter_pass(tokens: Vec<Token>, mut program: ProgramStore) -> Result<(Vec<Token>, ProgramStore), String> {
let mut tok_it = tokens.iter().peekable();
let mut output_tokens: Vec<Token> = Vec::new();
while let Some(&token) = tok_it.peek() {
match token {
// Remove doubled newline and comments, such that any sequence
// of newlines and comments gets shrinked to a single newline token
&Token::Newline => {
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
match next_token {
&Token::Newline | &Token::Comment(_) => {
continue;
}
_ => {
output_tokens.push(Token::Newline);
}
}
}
}
// remove comments just by ignoring them
&Token::Comment(_) => {
tok_it.next();
}
// on a define, create the empty FunctionInfo struct and put it into ProgramStore
&Token::Define => {
output_tokens.push(Token::Define);
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
if let &Token::Identifier(ref name) = next_token {
program = try!(program.add_function(name.clone(), FunctionInfo::named_new(name)));
} else {
return Err(format!("expected function name but found {:?}", next_token));
}
}
}
// simply copy all other tokens
_ => {
output_tokens.push(token.clone());
tok_it.next();
}
}
}
Ok((output_tokens, program))
}
pub fn blockify_pass(tokens: Vec<Token>) -> Result<LinkedList<Vec<Token>>, String>
|
Ok(block_list)
}
|
{
let mut tok_it = tokens.into_iter();
let mut block = Vec::new();
let mut block_list = LinkedList::new();
while let Some(token) = tok_it.next() {
match token {
Token::Define => {
if block.len() != 0 && block[0] == Token::Define {
block_list.push_back(block);
}
block = Vec::new();
}
_ => {}
}
block.push(token);
}
// Add last block to block list
block_list.push_back(block);
|
identifier_body
|
parser_utils.rs
|
use std::collections::LinkedList;
use std::iter::Iterator;
use std::vec::Vec;
use lexer::Token;
use interpreter::ProgramStore;
use interpreter::FunctionInfo;
/// This function filters out comments and doubled newlines
/// It also registers the functions with the program store
pub fn filter_pass(tokens: Vec<Token>, mut program: ProgramStore) -> Result<(Vec<Token>, ProgramStore), String> {
let mut tok_it = tokens.iter().peekable();
let mut output_tokens: Vec<Token> = Vec::new();
while let Some(&token) = tok_it.peek() {
match token {
// Remove doubled newline and comments, such that any sequence
// of newlines and comments gets shrinked to a single newline token
&Token::Newline => {
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
match next_token {
&Token::Newline | &Token::Comment(_) => {
continue;
}
_ => {
output_tokens.push(Token::Newline);
}
}
}
}
// remove comments just by ignoring them
&Token::Comment(_) => {
tok_it.next();
}
// on a define, create the empty FunctionInfo struct and put it into ProgramStore
&Token::Define => {
output_tokens.push(Token::Define);
tok_it.next();
if let Some(&next_token) = tok_it.peek() {
if let &Token::Identifier(ref name) = next_token {
program = try!(program.add_function(name.clone(), FunctionInfo::named_new(name)));
} else {
return Err(format!("expected function name but found {:?}", next_token));
}
}
}
// simply copy all other tokens
_ => {
output_tokens.push(token.clone());
tok_it.next();
}
}
}
Ok((output_tokens, program))
}
pub fn blockify_pass(tokens: Vec<Token>) -> Result<LinkedList<Vec<Token>>, String> {
let mut tok_it = tokens.into_iter();
let mut block = Vec::new();
let mut block_list = LinkedList::new();
while let Some(token) = tok_it.next() {
match token {
Token::Define =>
|
_ => {}
}
block.push(token);
}
// Add last block to block list
block_list.push_back(block);
Ok(block_list)
}
|
{
if block.len() != 0 && block[0] == Token::Define {
block_list.push_back(block);
}
block = Vec::new();
}
|
conditional_block
|
errors.rs
|
use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
|
FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoStringError);
Utf8(::std::str::Utf8Error);
IO(::std::io::Error);
}
errors {
Rados(e: u32) {
description("RADOS error")
display("RADOS error code {}: `{}`", e, get_error_string(*e).unwrap())
}
}
}
/// Convert the integer output of a librados API function into a `Result<()>`.
pub fn librados(err: i32) -> Result<()> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(())
}
}
/// Convert the integer output of a librados API function into a `Result<u32>`, returning the error
/// value casted to a `u32` if it's positive and returning `Err` otherwise.
pub fn librados_res(err: i32) -> Result<u32> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(err as u32)
}
}
/// Get the registered error string for a given error number.
pub fn get_error_string(err: u32) -> Result<String> {
let error = unsafe {
let err_str = libc::strerror(err as i32);
try!(
CStr::from_ptr(err_str)
.to_str()
.chain_err(|| "while decoding error string",)
)
};
Ok(error.to_string())
}
|
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError);
|
random_line_split
|
errors.rs
|
use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError);
FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoStringError);
Utf8(::std::str::Utf8Error);
IO(::std::io::Error);
}
errors {
Rados(e: u32) {
description("RADOS error")
display("RADOS error code {}: `{}`", e, get_error_string(*e).unwrap())
}
}
}
/// Convert the integer output of a librados API function into a `Result<()>`.
pub fn librados(err: i32) -> Result<()> {
if err < 0
|
else {
Ok(())
}
}
/// Convert the integer output of a librados API function into a `Result<u32>`, returning the error
/// value casted to a `u32` if it's positive and returning `Err` otherwise.
pub fn librados_res(err: i32) -> Result<u32> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(err as u32)
}
}
/// Get the registered error string for a given error number.
pub fn get_error_string(err: u32) -> Result<String> {
let error = unsafe {
let err_str = libc::strerror(err as i32);
try!(
CStr::from_ptr(err_str)
.to_str()
.chain_err(|| "while decoding error string",)
)
};
Ok(error.to_string())
}
|
{
bail!(ErrorKind::Rados(-err as u32));
}
|
conditional_block
|
errors.rs
|
use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError);
FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoStringError);
Utf8(::std::str::Utf8Error);
IO(::std::io::Error);
}
errors {
Rados(e: u32) {
description("RADOS error")
display("RADOS error code {}: `{}`", e, get_error_string(*e).unwrap())
}
}
}
/// Convert the integer output of a librados API function into a `Result<()>`.
pub fn librados(err: i32) -> Result<()> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(())
}
}
/// Convert the integer output of a librados API function into a `Result<u32>`, returning the error
/// value casted to a `u32` if it's positive and returning `Err` otherwise.
pub fn librados_res(err: i32) -> Result<u32> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(err as u32)
}
}
/// Get the registered error string for a given error number.
pub fn get_error_string(err: u32) -> Result<String>
|
{
let error = unsafe {
let err_str = libc::strerror(err as i32);
try!(
CStr::from_ptr(err_str)
.to_str()
.chain_err(|| "while decoding error string",)
)
};
Ok(error.to_string())
}
|
identifier_body
|
|
errors.rs
|
use std::ffi::CStr;
use libc;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
links {}
foreign_links {
Nul(::ffi_pool::NulError);
NulStd(::std::ffi::NulError);
FromBytesWithNul(::std::ffi::FromBytesWithNulError);
IntoString(::std::ffi::IntoStringError);
Utf8(::std::str::Utf8Error);
IO(::std::io::Error);
}
errors {
Rados(e: u32) {
description("RADOS error")
display("RADOS error code {}: `{}`", e, get_error_string(*e).unwrap())
}
}
}
/// Convert the integer output of a librados API function into a `Result<()>`.
pub fn librados(err: i32) -> Result<()> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(())
}
}
/// Convert the integer output of a librados API function into a `Result<u32>`, returning the error
/// value casted to a `u32` if it's positive and returning `Err` otherwise.
pub fn
|
(err: i32) -> Result<u32> {
if err < 0 {
bail!(ErrorKind::Rados(-err as u32));
} else {
Ok(err as u32)
}
}
/// Get the registered error string for a given error number.
pub fn get_error_string(err: u32) -> Result<String> {
let error = unsafe {
let err_str = libc::strerror(err as i32);
try!(
CStr::from_ptr(err_str)
.to_str()
.chain_err(|| "while decoding error string",)
)
};
Ok(error.to_string())
}
|
librados_res
|
identifier_name
|
fill.rs
|
use lyon::tessellation::FillOptions;
/// Nodes that support fill tessellation.
///
/// This trait allows the `Drawing` context to automatically provide an implementation of the
/// following builder methods for all primitives that provide some fill tessellation options.
pub trait SetFill: Sized {
/// Provide a mutable reference to the `FillOptions` field.
fn fill_options_mut(&mut self) -> &mut FillOptions;
/// Specify the whole set of fill tessellation options.
fn fill_opts(mut self, opts: FillOptions) -> Self {
*self.fill_options_mut() = opts;
self
}
/// Maximum allowed distance to the path when building an approximation.
fn fill_tolerance(mut self, tolerance: f32) -> Self {
self.fill_options_mut().tolerance = tolerance;
self
}
/// Specify the rule used to determine what is inside and what is outside of the shape.
///
/// Currently, only the `EvenOdd` rule is implemented.
fn fill_rule(mut self, rule: lyon::tessellation::FillRule) -> Self {
self.fill_options_mut().fill_rule = rule;
self
}
/// Whether to perform a vertical or horizontal traversal of the geometry.
///
/// Default value: `Vertical`.
fn fill_sweep_orientation(mut self, orientation: lyon::tessellation::Orientation) -> Self {
self.fill_options_mut().sweep_orientation = orientation;
self
}
/// A fast path to avoid some expensive operations if the path is known to not have any
/// self-intersections.
///
/// Do not set this to `false` if the path may have intersecting edges else the tessellator may
/// panic or produce incorrect results. In doubt, do not change the default value.
///
/// Default value: `true`.
fn handle_intersections(mut self, handle: bool) -> Self
|
}
impl SetFill for Option<FillOptions> {
fn fill_options_mut(&mut self) -> &mut FillOptions {
self.get_or_insert_with(Default::default)
}
}
|
{
self.fill_options_mut().handle_intersections = handle;
self
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.